Hi I am attempting to define a 2D array in JS but I seem to get two errors preventing me and I am not sure where I am going wrong. i is simply from a for loop - it has been defined. Even if I replace i with 0 same error occurs. My code:
let leds[i][i] = randint(0, 10);
This results in the error:
'=' expected.
however removing the let:
leds[i][i] = randint(0, 10);
results in a different error:
Type 'number' is not assignable to type 'undefined'.
I am using the JS editor for the BBC Microbit. Thanks in advance.
The variable leds
needs to be defined as an array before it can be used as one. Then you can add elements to it using the push
method; and these elements can be other (nested) arrays. For example:
//set leds as an empty array
let leds = [];
//add to the array
leds.push([]);
leds[0] = [1,2,3];
leds.push([]);
leds[1] = [4,5,6];
leds.push([7,8,9]);
//change an array value
leds[1][1] = 0;
console.log(leds);