1

I do console.log(entry.passengers) I got this

[{"name":"james"},{"name":"john"},{"name":"abc"}]

But why I got undefined when I used forEach?

entry.passengers.forEach(function(i,obj){
  console.log(obj.name); // undefined
});
3
  • What does console.log(obj) show? Commented Oct 28, 2015 at 4:26
  • Look at the order of arguments to the callback in developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Oct 28, 2015 at 4:27
  • You have been corrupted, the order of parameters passed to the callback is value, index. Commented Oct 28, 2015 at 4:29

1 Answer 1

4

The first parameter to forEach is the element and second parameter is the index.

entry.passengers.forEach(function(obj, i) {
//                                ^^^  ^ Change the sequence

var arr = [{
  "name": "james"
}, {
  "name": "john"
}, {
  "name": "abc"
}];

arr.forEach(function(e, i) {
  console.log(e, i);

  document.write(e.name + '<br />');
});

Sign up to request clarification or add additional context in comments.

4 Comments

so it's opposite of $.each?
@user3519144 the order of parameters, yes.
thanks! didn't know that! must be careful next time.
@user3519144—yes, jQuery has it backwards.

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.