如何将值推送到多维数组

时间:2012-12-16 13:18:49

标签: javascript jquery

我无法弄清楚如何将值推送到动态多维数组。这是我的代码:

function compareNumbers(){
    var count = $('.finishedRow').length;
    var inputtedNums = new Array();
    for(var i=0; i<count; i++){
        $('.finishedRow').eq(i).find('li').each(function(j){
            inputtedNums[i].push($(this).text());
        });
    }
    console.log(inputtedNums);
}

所以说,例如,有3个finishedRow选择器,每个finishedRow选择器包含4个li元素,其值为firstsecond,{ {1}},third。我希望我的fourth变量看起来像:

inputtedNums

现在我的代码出现了错误:inputtedNums = [ ["first", "second", "third", "fourth"], ["first", "second", "third", "fourth"], ["first", "second", "third", "fourth"] ]

我确信我在这里缺少一些基本的东西。

1 个答案:

答案 0 :(得分:4)

您需要首先初始化每个嵌套数组。

for(var i = 0; i < count; i++) {
    inputtedNums[i] = new Array();
    $('.finishedRow').eq(i).find('li').each(function(j) {
        inputtedNums[i].push($(this).text());
    });
}