简体   繁体   中英

How to push values to a multi-dimensional array

I can't figure out how to push values to a dynamic multi-dimensional array. This is the code i have:

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);
}

So say there are, for example, 3 finishedRow selectors and each finishedRow selector contains 4 li elements with values of first , second , third , fourth . I want my inputtedNums variable to look like:

inputtedNums = [
   ["first", "second", "third", "fourth"],
   ["first", "second", "third", "fourth"], 
   ["first", "second", "third", "fourth"] 
]

As my code is now I get the error: Cannot call method 'push' of undefined .

I'm sure I'm missing something fundamental here.

You need to initialize every nested array first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM