how to assign values to multidimensional arrays in javascript?

后端 未结 2 1658
萌比男神i
萌比男神i 2021-01-13 13:09

I tried to do this with:

arr[i][j] = \'whatever\';

but I get some kind of error \"cannot convert to object...\"

相关标签:
2条回答
  • 2021-01-13 13:18

    I'm going to guess that you haven't initialized a[i] when you try to treat it like an array. If you haven't initialized a[i] to be an array when you say a[i][j], then it will be undefined (or something else that isn't an array or object) and that doesn't know what [j] means, hence your "cannot convert to an object" error. You need something more like this:

    var a = [ ];
    for(var i = 0; i < 10; ++i) {
        a[i] = [ ];
        for(var j = 0; j < 10; ++j) {
            a[i][j] = 42; // a[i] is now an array so this works.
        }
    }
    
    0 讨论(0)
  • 2021-01-13 13:30

    Set Like

    a[3]["fieldName"]="xxxx";
    
    0 讨论(0)
提交回复
热议问题