Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【JavaScript】数组对象与 arguments #69

Open
swiftwind0405 opened this issue Nov 23, 2020 · 0 comments
Open

【JavaScript】数组对象与 arguments #69

swiftwind0405 opened this issue Nov 23, 2020 · 0 comments

Comments

@swiftwind0405
Copy link
Owner

swiftwind0405 commented Nov 23, 2020

类数组对象的概念

类数组对象:只包含使用从零开始,且自然递增的整数做键名,并且定义了length表示元素个数的对象,我们就认为它是类数组对象!

举个例子:

let ary = [2,2,4,5];
let o = {0:23,1:23,2:32,length:3};
console.log(ary[0],o[0]);//2,23
console.log(ary.length,o.length);//4,3

这里的 o 就是一个类数组对象。
一般我们常用到的类数组对象如:arguments,获取的元素集合。

类数组对象不仅在效果上与数组相似,在某些操作上也是相同的。

//定义数组和类数组对象
let ary1 = [2,5,23,5,52];
let oo = {0:4,1:32,2:324,length:3};

//读写操作
console.log(ary1[1],oo[1],ary1["length"],oo["length"]);//5,32,5,3
ary1[0] = 4;
oo[0] = 6;
console.log(ary1[0],oo[0]);//4,6

//遍历
for(var i=0;i<ary1.length;i++){
	console.log(ary1[i]);
}
for(var i=0;i<oo.length;i++){
	console.log(oo[i]);
}

可以从数据结构上把js中的数组归为对象,因为我们可以使用对象来模拟数组,这里仅仅说的是数据结构上,其实它们本身所继承来的方法和一些属性是不同的。

类数组对象转换为数组

const typedArray = {0: '1', 1: '2', length: 2};
const array = Array.prototype.slice.call(typedArray)

可以转数组的对象,必须符合两个条件:

  1. 对象的元素索引使用数字。
  2. 对象必须有length属性。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant