gpt4 book ai didi

javascript - 从对象中排除变量

转载 作者:行者123 更新时间:2023-11-30 23:44:33 24 4
gpt4 key购买 nike

所以基本上我明白你可以通过这两种方式循环遍历数组。

var testarray = new Array(1,2,3,4);
for(i in testarray)console.log(testarray[i]);
//outputs 1,2,3,4
for(var i=0;i<testarray.length;i++) console.log(testarray[i]);
//outputs 1,2,3,4

我的问题是如何复制/模拟该数组。支持两种 for 循环方法吗?因为当我做同样的事情但我创建自己的函数时,它在第一个 for 循环中包含长度。

function emulatearray(){
for(var i = 0;i<arguements.length;i++)this[i]=arguments[i];
this.length = i;
}
var testarray = new emulatearray(1,2,3,4);
for(i in testarray)console.log(testarray[i]);
//outputs 1,2,3,4,null
for(var i=0;i<testarray.length;i++) console.log(testarray[i]);
//outputs 1,2,3,4

最佳答案

for...in语句不应该用于迭代数组。

引用Mozilla Dev Center :

for...in Statement


Although it may be tempting to use this as a way to iterate over an Array, this is a bad idea. The for...in statement iterates over user-defined properties in addition to the array elements, so if you modify the array's non-integer or non-positive properties (e.g. by adding a "foo" property to it or even by adding a method or property to Array.prototype), the for...in statement will return the name of your user-defined properties in addition to the numeric indexes.

Also, because order of iteration is arbitrary, iterating over an array may not visit elements in numeric order. Thus it is better to use a traditional for loop with a numeric index when iterating over arrays.

关于javascript - 从对象中排除变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3498129/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com