It is said that forEach() method is used to loop over any array like object .But here
Array.prototype.forEach.call({1:"a",2:"b"},function(eleVal,ele){alert(eleVal+":"+ele)})
The above code dont work ,why??
Because {1: "a", 2: "b"} is not an array, it's an object. Array.forEach requires that its target has a length property, which this object does not.
Try with an array such as ["a", "b"] and it will work, or alternatively with the array look-alike
{0: "a", 1: "b", length: 2}
.forEach should work. Note that it requires the object to have a length property.Another way to do it. I prefer this one since it doesn't modify the original object.
var obj = {1:"a", 2:"b"};
for(var i in obj) { if(obj.hasOwnProperty(i)) console.log(i + ':' + obj[i]); }
forEach method. And consider filtering using hasOwnProperty within your loop. Your side effects will be different from the original.