繁体   English   中英

JavaScript-数组的行为类似于对象

[英]JavaScript - Array behaves like object

我想问一个关于JavaScript数组的问题。 当我们使用for..in循环进行迭代时,数组的行为是否像对象一样? 我的意思是在这种情况下索引可以充当属性(键)的角色。

尽管可以在数组上执行..in语法,但是您不应该这样做,因为您将迭代可能已分配给数组的所有属性。

Example:
var array = [0, 1];
array.three = 2;
for (var p in array){
    console.log(array[p]); //print 0, 1, 2
}

for(var i = 0; i < array.length; i++){
    console.log(array[i]); //prints 0, 1
}

因此,在处理数组时,应始终使用for var i方法,以避免遇到意外行为。

正如JS中的所有内容一样,数组是一个对象。

这意味着您可以将数组用作原型:

var obj = Object.create([]);
console.log(obj instanceof Array); // true
obj[0] = "value 1";
obj.test = "value of property test";
for(var i in obj) console.log(obj[i]); // "value 1" "value of property test"

或您将对对象执行的其他任何操作,包括使用for ... in循环。

但是,将使用数组+1的最高(整数)索引来更新length属性。

var arr = ["one","two"];
arr.length; // 2

这就是为什么只在迭代数组的值时不建议for ... in循环中使用for ... in的原因:您可以使用for(var i=0,var l=arr.length;i<arr.length;i++)

是的,您可以像访问对象一样访问数组仅当数组string时

var sdf = [];
sdf['asd'] =45;
sdf[32] =8674;

console.log(sdf.asd)  // WORKS
console.log(sdf.32)  // Error

Array.prototype.forEach是您想要的。 请注意浏览器的支持或使用可纠正不受支持的浏览器的框架: http : //kangax.github.io/compat-table/es5/#Array.prototype.forEach

for in应该用于遍历对象属性,因为不能保证顺序。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM