2

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.

2 Answers2

3

First of all, technically in the javascript there is no such thing as 2D array. That you are using is just an array inside the Array.

For example you can create 4X4 array like:

>>> const array = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 11, 12],
    [13, 14, 15, 16]
]
>>> array[1][1]
6

So in your case, you need to create an empty multidimensional array and only you can assign values.

There is a shortcut to create 10x10 array with 0 as default value:

>>> const a = new Array(10).fill(new Array(10).fill(0))
>>> a
(10) [Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10), Array(10)]
0: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
1: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
2: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
3: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
4: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
5: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
6: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
7: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
8: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
9: (10) [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
length: 10
__proto__: Array(0)

Finally when you have your array, you can get/assign values by index'es:

a[9][9] = 10
10
a[9][9]
10
KiraLT
  • 2,385
  • 1
  • 24
  • 36
  • Using fill will create an array of exactly the same objects. Now, when you change the value in one row, the others will change too! – Jamie McLaughlin May 31 '23 at 12:23
2

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);
sbgib
  • 5,580
  • 3
  • 19
  • 26