js深入学习专题 —— 类数组的对象和数组对象的区别和联系

类数组对象:(看例子)           

var a = {};       

var i =10;

while(i<10){

 a[i] = i*i;

i++;

}

数组对象呢:

var b = [];

var i =0;

while(i<10){

b[i] = i*i;

i++;

}

其实你从源代码上面去看也没有什么大的区别:

但是js中是支持  1: 类名【属性名称】 = 值  相当于 2:类名.属性名称 = 值 

要是你想在类中使用动态的属性  就必须用第一个   

下面看下下区别吧:

类数组对象:

console.log(typeof a);//object 注意:数组也是对象哦

console.log(a); //  Object {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81} 很明显对象啊

console.log(a.length); //undefined  区别就在这了  类数组对象没有长度的属性和数组的方法

console.log(Object.prototype.toString.call(a));//[object Object] 

数组对象:

console.log(typeof b);//object

console.log(b);//  [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]  很明显数组啊 

console.log(b.length); //8

console.log(Object.prototype.toString.call(b));//[object Array]

通过上述的例子肯定就明白了:哈哈 

在上一个判断是对象还是数组的方法

var isArray = Function.isArray || function(o){

 return typeof o === "object" && Object.prototype.toString.call(o) == "[object Array]";

}


版权声明:本文为shachao888原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
THE END
< <上一篇
下一篇>>