2

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??

3 Answers 3

4

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}
Sign up to request clarification or add additional context in comments.

4 Comments

but it is array like object
It's more akin to a hash. It's not an array.
@Maizere: The ECMAScript specification details exactly how .forEach should work. Note that it requires the object to have a length property.
Since there is more than one person downvoting this answer, something must be wrong with it. Can we have some feedback please?
3

Add a .length property to the object and it'll work.

Please note that you'll index will start at 0, so the first element will be undefined.

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

Comments

1

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]); }

3 Comments

You can improve your answer by saying why you have demonstrated this form of looping, when the OP has specified the forEach method. And consider filtering using hasOwnProperty within your loop. Your side effects will be different from the original.
@Maizere you said that your code didn't work, I only showed other way to solve the problem. Many people ask why their code doesn't work, when they only don't know a better way to do it. I had the best of intentions.
@Seza edit ur question so that i can upvote it ,thank u for ur exercise

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.