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.

0

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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

3 Comments

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!
Yes, the shortcut second example is very bad guidance. Never pass an array to .fill(). Just follow the final example then a[8][9] and a[7][9] and ... a[0][9] will all be 10.
Specifically, never pass anything mutable to .fill(). Objects and arrays are mutable, strings and primitives are not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.