javascript - 遍历空 javascript 数组返回数组对象函数

标签 javascript arrays loops for-loop associative

我注意到,在我的 javascript 中,如果我创建一个空数组,将其作为关联数组循环,并打印出内容,它会返回类似于 Array Object 类本身的函数。这是我的代码:

var test = new Array();
for(var i in test){
    document.write(i + " " + test[i] + "<br>");
}
alert(test.length); // this returns 0

上面的代码打印了以下内容(我省略了一些输出,因为它有点长)

$family function (){return u; }
$constructor function Array() { [native code] }
pop function pop() { [native code] }
push function push() { [native code] }
reverse function reverse() { [native code] }
shift function shift() { [native code] }
sort function sort() { [native code] }
splice function splice() { [native code] }
unshift function unshift() { [native code] }
concat function concat() { [native code] }
join function join() { [native code] }
slice function slice() { [native code] }
indexOf function indexOf() { [native code] }
etc...

我注意到,如果我使用 for 循环遍历数组,即:

for(var i = 0; i < test.length; i++)

浏览器没有打印出任何东西(这是应该发生的)

谁能解释为什么当我以另一种方式循环时我从一个空数组中得到一堆函数?以防万一,我使用的是 mootools v1.3。提前致谢。

最佳答案

摆脱所有扩展 Array.prototype 的东西.扩展默认类型的原型(prototype),如 ArrayObject不好,会导致这样的问题。

在保留原型(prototype)扩展的同时规避问题的简单方法是添加 if(!test.hasOwnProperty(i)) continue;查看。 (obj.hasOwnProperty(key)true 如果该属性在对象本身上,而不仅仅是在其原型(prototype)链中的某处)

除此之外,你不应该使用 for..in遍历数组时循环 - 使用 for(var i = 0; i < array.length; i++)在这种情况下。

关于javascript - 遍历空 javascript 数组返回数组对象函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5845048/

相关文章:

javascript - Angular2组件单元测试

javascript - 将对象列表推送到angularjs中的另一个对象

c - 简单计数器在 C 中不起作用

java - 在 for 循环中设置唯一的计时器

javascript - 如何将数组拆分为两个子集并使数组的子值之和尽可能相等

javascript - 添加新元素时,Vue-js 从文本框中删除了选定的日期

javascript - 使用 jquery/javascript 查找包含标题的 csv 文件

arrays - 在不创建新数组的情况下反转字符数组

Java:创建一个以字母字符为索引的数组

java - 将循环结果放入java中的字符串中