53

I'm using Google Chrome's Console window to try and figure out why I'm not able to loop over an array in javascript.

I have a javascript object calledmoveResult that looks like this:

enter image description here

I'm trying to loop over theMoveParts in javascript like this:

for (var movePart in moveResult.MoveParts) {    console.log(movePart.From);};

I always getundefined instead of the actual value. However, If I try to access the first item explicitly I get what I want, like this:

console.log(moveResult.MoveParts[0].From);

The result of this is"b1".

Why isn't my loop working?

I've also tried a foreach:

moveResult.MoveParts.foreach(function (movePart) {    console.log(movePart.From);};
askedDec 23, 2014 at 18:16
PeteGO's user avatar
0

1 Answer1

20

I'm trying to loop over the MoveParts in javascript like this:

for (var movePart in moveResult.MoveParts) {    console.log(movePart.From);};

I always get undefined instead of the actual value.

Don't usefor-in to loop through arrays, that's not what it's for.for-in is for looping through object properties.This answer shows various ways to loop through arrays.

The reason yourfor-in didn't work is thatmovePart is thekey, not the actual entry, so if you were using an object (not an array!) you would have usedmoveResult.MoveParts[movePart].From.

YourforEach version only failed because:

  1. It'sforEach, notforeach. Capitalization matters in JavaScript.

  2. You were missing the closing) on the function call.

The answer linked above has full examples offorEach and others, but here's how yours should have looked:

    moveResult.MoveParts.forEach(function (movePart) {    // Capital E -----------^        console.log(movePart.From);    });//   ^---- closing )
answeredDec 23, 2014 at 18:22
T.J. Crowder's user avatar
Sign up to request clarification or add additional context in comments.

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.