无法进入我的for循环(Javascript)

时间:2015-05-21 14:15:24

标签: javascript

我正在尝试迭代变量pieces,但不知何故它没有触发。在下面的函数中,pieces.length变为4,但piecesNew变为[] - 而且console.log(i)永远不会到达。

发生了什么事?

self.reworkPieces = function(pieces) {

        var piecesNew = [];

        console.log(pieces.length)

        for (var i; i <= pieces.length; i++) {

            console.log(i)

            piecesNew[i] = {
                c: pieces[i].r,
                r: pieces[i].c,
                p: i
            }

        }

        console.log(piecesNew)

        return piecesNew;

    }; 

5 个答案:

答案 0 :(得分:7)

undefined不是小于大于任何数字。

var i; // undefined
i < 10; // false
i > 10; // false

您只需确保i等于0

您还希望i永远不等于pieces.length,因此请使用<代替<=(数组的最后一个索引始终为length - 1,例如,长度为3的数组具有索引0,1和2 - 第一个索引始终为0,而​​不是1)

所以:

for (var i = 0; i < pieces.length; i++) {
    ...

答案 1 :(得分:3)

定义变量i的值var i = 0

self.reworkPieces = function(pieces) {

        var piecesNew = [];

        console.log(pieces.length)

        for (var i = 0; i <= pieces.length; i++) {

            console.log(i)

            piecesNew[i] = {
                c: pieces[i].r,
                r: pieces[i].c,
                p: i
            }

        }

        console.log(piecesNew)

        return piecesNew;

    }; 

答案 2 :(得分:2)

self.reworkPieces = function(pieces) {

    var piecesNew = [];

    console.log(pieces.length)

    for (var i = 0; i <= pieces.length; i++) {

        console.log(i)

        piecesNew[i] = {
            c: pieces[i].r,
            r: pieces[i].c,
            p: i
        }

    }

    console.log(piecesNew)

    return piecesNew;

}; 

答案 3 :(得分:2)

变化:

 for (var i; i <= pieces.length; i++)

要:

 for (var i = 0; i < pieces.length; i++)

答案 4 :(得分:1)

最初初始化var i = 0然后它将起作用

self.reworkPieces = function(pieces) {

            var piecesNew = [];

            console.log(pieces.length)

            for (var i = 0; i <= pieces.length - 1; i++) {

                console.log(i)

                piecesNew[i] = {
                    c: pieces[i].r,
                    r: pieces[i].c,
                    p: i
                }

            }

            console.log(piecesNew)

            return piecesNew;

        };