0

The following code:

let s=[[],[]];
let k=0;
while (k<(JSON.parse(req.responseText).length)){
s[k][0] =dataBack[k].ModuleCode;
s[k][1] =dataBack[k].ModuleDescription;
k=k+1;
}

Should populate an array (s) with the data from an Ajax responce. But this is not the case, since when k=2 (3d item) I get an error:

code.js:288 Uncaught TypeError: Cannot set property '0' of undefined

Searching on StackOverflow, I found this link: How to create empty 2d array in javascript? describing what I have done to declare my Array.

I am expecting the above code to store the returned values into the (s) array. But I get the error described above.

  • 3
    `s[2]` will be `undefined` since `s` only contains two lists. What are you trying to do there? – Carcigenicate May 19 '19 at 22:08
  • Btw - you're parsing the response text on EVERY iteration. That's a bit wasteful, I think. Better parse it once at the start and set to a variable. – Vilx- May 19 '19 at 22:45

3 Answers3

3

Change your code a bit to add arrays as needed:

let s=[];
let k=0;
while (k<(JSON.parse(req.responseText).length)){
    s.push([]);
    s[k][0] =dataBack[k].ModuleCode;
    s[k][1] =dataBack[k].ModuleDescription;
    k=k+1;
}
Oleg
  • 6,124
  • 2
  • 23
  • 40
1

Hope this makes it clear why you're failing:

let s = [  [],                  []        ];
//        ^^^^ s[0]            ^^^^s[1]
connexo
  • 53,704
  • 14
  • 91
  • 128
0

Javascript will let you ASSIGN to positions in the array that don't exist yet. eg:

var a=[];
a[10]=12345;
console.log(a);
//Output: [ <10 empty items>, 12345 ] 

However in your code you are ACCESSING the undefined position first and then trying to modify what is returned.

Adding an intermediate step it might clear up why it doesn't work:

let s=[[],[]];
let k=0;
while (k<(JSON.parse(req.responseText).length)){

    var tmp=s[k];   //When k>=2  tmp is undefined. 

    tmp[0] =dataBack[k].ModuleCode;      //Trying to add a property at  0 on undefined object
    tmp[1] =dataBack[k].ModuleDescription;
    k=k+1;
}

@Oleg has given a nice work around in his answer but using s.push([]) to ensure the value you are accessing is definite for before the subsequent modifications.

Alternatively you could assign an empty array directly s[k]=[] before modification.

drclaw
  • 2,463
  • 9
  • 23