简体   繁体   中英

Javascript array becomes null

I defined two-dimensional array, tried to fill it in nested loop, but it fill only first dimension with right values, other dimensions are filled with null(or undefined), thanks.

var Arr = [];
var i =0;

for(i=0;i<13;i++)
{
  Arr[i]=[];
}

var a=0,b=0;

for(a=0;a<13;a++)
{
  for(b=0;b<13;b++)
  {
    Arr[[a][b]]=AnotherArrWithRightValues[(13 * a) + b];
  }
}

Arr[[a][b]]应该是Arr[a][b]

Loksly's answer is correct, but implemented in a different way. To answer your question, replace Arr[[a][b]] with Arr[a][b] .


Full Code :

var Arr = [];

for(var a = 0 ; a < 13 ; a++) {
  Arr[a] = [];
  for(var b = 0 ; b < 13 ; b++) {
    Arr[a][b]=AnotherArrWithRightValues[(13 * a) + b];
  }
}

Just for the record, another way to achieve the same:

var Arr = [];
var i = 0, tmp;
var a, b;

for(a = 0; a < 13; a++){
    tmp = [];
    for(b = 0; b < 13; b++){
        tmp.push(AnotherArrWithRightValues[i++]);
    }
    Arr.push(tmp);
}

Try this,

var arr =[];

for(var a=0;a<13;a++)
  {
    arr[a] = new Array();
    for(var b=0;b<13;b++)
      {
        arr[a].push((13 * a) + b);
      }
  }

i hope this will help you

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