使用Array.prototype.forEach()方法

Using Array.prototype.forEach() Method

本文关键字:方法 forEach Array prototype 使用      更新时间:2023-09-26

据说forEach()方法用于遍历任何数组,比如对象,但是这里

Array.prototype.forEach.call({1:"a",2:"b"},function(eleVal,ele){alert(eleVal+":"+ele)})

上面的代码不工作,为什么??

因为{1: "a", 2: "b"}不是数组,它是对象。Array.forEach要求它的目标具有length属性,而这个对象没有。

尝试使用一个数组,如["a", "b"],它将工作,或者使用与数组相似的

{0: "a", 1: "b", length: 2}

给对象添加一个.length属性,它就会起作用了。

请注意,你的索引将从0开始,所以第一个元素将是未定义的。

[].slice.call({1: 'a', 2: 'b', length: 3})
[undefined × 1, "a", "b"]

另一种方法。我更喜欢这个,因为它不修改原始对象。

var obj = {1:"a", 2:"b"};
for(var i in obj) { if(obj.hasOwnProperty(i)) console.log(i + ':' + obj[i]); }