Exploring the Power of 2D Arrays in JavaScript

Hey there! I'm having trouble defining a 2D array in JS. Two errors are getting in my way and I can't figure out what's going wrong. i is generated by a for loop - it's defined. Even when I try replacing i with 0, the same error occurs. Here's my code:

let leds[i][i] = randint(0, 10);

When trying this, I get the following error:

'=' expected.

But if I remove the let:

leds[i][i] = randint(0, 10);

I encounter a different error:

Type 'number' is not assignable to type 'undefined'.

I'm using the JS editor for the BBC Microbit. Appreciate any help!

Answer №1

To effectively use the variable leds as an array, it must first be defined as one. You can then populate this array by utilizing the push method to add elements, which can also include nested arrays. See below for an example:

// Define leds as an empty array
let leds = [];

// Populate the array with nested arrays
leds.push([]);
leds[0] = [1, 2, 3];

leds.push([]);
leds[1] = [4, 5, 6];

leds.push([7, 8, 9]);

// Modify a value within the array
leds[1][1] = 0;

console.log(leds);

Answer №2

First and foremost, it's important to note that in JavaScript there is no explicit 2D array data structure. What you typically refer to as a 2D array is essentially an array of arrays.

For instance, you can create a 4x4 array like this:

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

In your scenario, you would need to initialize an empty multidimensional array and then populate it with values as needed.

A quick way to create a `10x10` array with `0` as the default value is:

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

Once you have your array set up, you can access and modify values using index notation:

a[9][9] = 10
10
a[9][9]
10

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can a single Axios request in JavaScript include both a Body and Files?

Is it possible to send both a file and body with the POST request below in axios? axios.post("http://localhost:3000/upload", formData) How can I include something in the body:{} section as well? Server response: files: { myFile: { nam ...

Updating the state in a React array of objects can be achieved by checking if the specific id already exists in the array. If

In the scenario where the parent component receives an object from the child component via a callback function, I need to verify the existence of an object with a specific rowID. If it exists, the object should be updated with the passed value "val"; oth ...

Tips for utilizing pre-installed validation regulations in VeeValidate 4?

Currently transitioning from Vue 2 to Vue 3, I am interested in utilizing VeeValidate 4 for my validations. However, it seems that the documentation does not provide any information on using built-in rules such as min, max, alpha_spaces, etc. Do I need to ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

Difficulty encountered when applying date filtering on a specific filter in the MUI-DataGrid

Software Version: "@mui/x-data-grid": "^6.2.1" I have a script that generates columns for the DataGrid as shown below (only including relevant code) if (prop === "date" || prop === "dateModified" || prop === "n ...

The issue with viewing next/image properly only occurs on desktops using a responsive layout. I would like for the image

<Image src={APIImagePath} alt={t("common:tokens")} layout="fill" className={styles.img} /> Showing on a desktop screen: https://i.stack.imgur.com/gT2ZF.png Viewing on a tablet: https://i.stack.imgur.com/yeABR.png ...

What is the method for retrieving all 'name' values within a JSON array?

I am currently working on a project using Angular and I have a JSON file. I need to extract all the 'name' values from the array. Ideally, the output should look something like this: ['Sony', 'Apple', 'Sony'] JSON: ...

Multiple charts experiencing disappearing x-axis labels on Flot

When trying to display two separate bar graphs, the x-axis labels seem to disappear. However, when only one graph is displayed, the labels show up perfectly fine. Any thoughts on why this might be happening? Here is the code snippet for displaying two gr ...

How can jQuery determine the amount of line breaks within a div element?

My div wrap size is a percentage of the screen width, containing multiple .item divs that break into new lines as the window size decreases. I attempted to calculate the total number of boxes that could fit based on their widths compared to the container ...

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

Every time I try to upload image files to cloudinary, I encounter this frustrating error message

https://i.stack.imgur.com/kRYVZ.png The issue at hand revolves around node and the challenge of using the https module with new certificates, proving to be unsuccessful... The proposed solution is ambiguous, leaving me unsure how to proceed and resolve thi ...

Customize your error messages in AJAX requests

The form on my index.php page submits to process.php, triggering the execution of the code below: $(document).ready(function() { $('#login_button').click(function() { event.preventDefault(); var formData = { 'email' ...

Issue: Module 'connect' is not found?

Hey there! I'm fairly new to the world of servers, and I've been learning by watching YouTube tutorials. Following one such tutorial, I installed 'connect' using npm in my project folder. Here's the structure of my project: serv ...

Displaying Well-Formatted XML in Angular2 Using Typescript

After receiving this XML string from the server: <find-item-command xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" find-method="Criteria" item-class="com" only-id="false" xsi:schemaLocation=""> <criteria> <criterion> <descripto ...

"Keeping your HTML content up-to-date with AngularJS dynamic updates

I've noticed that when I upload changes to my AngularJS HTML partial files, there is a caching issue where the old data is displayed. It takes a few refresh actions before the changes become visible. Is there a way to make these changes appear immedi ...

Experiencing challenges in integrating fundamental Javascript elements on a chat page

My chat page skeleton is in place, but I'm facing challenges in connecting all the pieces. My goal is to send messages to the server whenever a user clicks 'send', and to update the displayed messages every 3 seconds. Any insights, tips, or ...

verification tool for a less file's syntax

Searching for a tool to validate a specific less file at the syntax level. The issue lies in the validator not recognizing dependencies or detecting declared mixins. Many existing less processors do not work due to missing dependencies that cannot be prov ...

Modify the contents of a textbox by editing the text as you type

Text within the text box follows this format: login -u username -p password When entering this text, I want to substitute 'password' with a series of '*'s equal in length. For example: 'login -u <a href="/cdn-cgi/l/email-prot ...

Having trouble reaching a public method within an object passed to the @Input field of an Angular component

My configurator object declaration is as follows. export class Config { constructor(public index: number, public junk: string[] = []) { } public count() : number { return this.junk.length; } } After declaring it, I pass it into the input decorated fi ...

Updating the Animation for Datepicker Closure

While using the date picker, I want it to match the width of the input text box. When closing the date picker, I prefer a smooth and single motion. However, after selecting a from and to date, the datepicker no longer closes smoothly. I have attempted sol ...