Loop Over Array in Javascript

This question already has an answer here:

  • For-each over an array in JavaScript? 23 answers

  • 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 use for-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 your for-in didn't work is that movePart is the key, not the actual entry, so if you were using an object (not an array!) you would have used moveResult.MoveParts[movePart].From .

    Your forEach version only failed because:

  • It's forEach , not foreach . Capitalization matters in JavaScript.

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

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

        moveResult.MoveParts.forEach(function (movePart) {
        // Capital E -----------^
            console.log(movePart.From);
        });
    //   ^---- closing )
    

    尝试

    moveResult.MoveParts.map(function (movePart) {
        console.log(movePart.From);
    };
    
    链接地址: http://www.djcxy.com/p/12060.html

    上一篇: 为什么我在控制台中获得'未定义'?

    下一篇: 在Javascript中循环数组