Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to assign values to multidimensional arrays in javascript?

I tried to do this with:

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

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

like image 934
NickTheDick Avatar asked Apr 30 '11 23:04

NickTheDick


2 Answers

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.
    }
}
like image 160
mu is too short Avatar answered Nov 15 '22 00:11

mu is too short


Set Like

a[3]["fieldName"]="xxxx";
like image 20
Mohit Malik Avatar answered Nov 14 '22 23:11

Mohit Malik