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

What is the best way to choose just the items with a distinct key from within this jQuery assortment?

[Object, Object, Object, prevObject: jQuery.fn.init[3], context: undefined] 0: Object 1: 1 2: 2 3: 7 __proto__: Object 1 : Object 1: 6 2: 2 3: 5 6: 15 __proto__: Object 2 : Object 1: 3 2: 2 3: 5 5: 7 ...

Determining the dimensions of a div with a scrollbar using Jquery

Is there a way to get the width and height of a div with scroll that includes both visible and hidden content using JQuery? If anyone has a solution for getting these values, please share. <div id="area" class="divLeftCem area"> <div id="pan ...

Ensure the browser back button navigates to the login page seamlessly, without displaying any error

A scenario I am working on involves a Login jsp that accepts a user email and sends it to a servlet. If the provided email is not found in the database, the servlet redirects back to Login.jsp with an attribute "error". Within the header of Login.jsp, ther ...

Concealing Contact Form Using Javascript

Upon making adjustments to a website, I encountered an issue with the contact form. The form is meant to be hidden on page load and only appear when the envelope icon is clicked. However, currently the form is visible by default, and clicking the envelope ...

I am struggling to apply custom CSS styles to the scrollbar within a Card component using MUI react

import React from "react"; import Card from "@mui/material/Card"; import CardActions from "@mui/material/CardActions"; import CardContent from "@mui/material/CardContent"; import CardMedia from "@mui/material/Ca ...

I am currently facing a challenge in animating my ng-show/ng-hide animation

This particular issue has been widely recognized and discussed multiple times in various forums. Despite the extensive search, I have not come across satisfactory solutions. var aniApp = angular.module("aniApp", []); aniApp.controller('mainCtrl&ap ...

Typescript: Shifting an image to the left and then returning it to the right

As a newcomer to Typescript, JavaScript, and front-end development, I am experimenting with creating a simulation of an AI opponent's "thinking" process when playing cards in a game. The idea is to visually represent the AI's decision-making by s ...

Next.js encountered a surprising conclusion to the JSON input

After retrieving data from /api/notes/1, the following JSON object is received: { "id":1, "author":1, "title":"First Note", "excerpt":"Just a note, blah blah blah", "body":"First no ...

ObservableResolve(): Unleashing the power of RxJS5 for handling asynchronous data streams

Hey there! To dive deeper into RxJS, I thought of creating my own custom Rx operator. So here's a straightforward one that seems to be working smoothly: Rx.Observable.prototype.multiply = function (input) { const source = this; return Rx.O ...

Identify 404 errors in multi-file routes with Express

Recently, I've been diving into using Express and I'm facing some challenges with detecting 404 errors. In my main file app.js, I launch the server and specify different files to handle various requests. For instance: const app = express(); app ...

Create an asynchronous method within an object-oriented programming (OOP) class

Presenting my Activity class. export class Activity { _name: string _goIn: boolean constructor(name: string) { this._name = name; this._goIn = false; } isGoIn() { return this._goIn; } setGoIn() { // instructions to asyn ...

Tips for effectively showcasing div elements

https://jsfiddle.net/qz8hL574/1/ for (var key in table) { if (table.hasOwnProperty(key)) { $('<div class="element"></div>').appendTo('#list'); document.getElementsByClassName("element")[key].innerHTML = ...

Tips for effectively utilizing the useDraggable and useSortable hooks within the dnd-kit library

I'm currently working on developing a basic calculator using React and dnd-kit. The idea is to have draggable elements in the calculator that can be sorted within a droppable area with smooth animation effects. However, I've encountered an issue ...

Testing Vue Components - Simulating the return value of a plugin

I have a unique scenario where I need to mock the return value of a custom plugin without importing it directly into my test. By creating a mock function for the plugin, I can easily achieve this goal. However, I am unsure how to change the return value of ...

Why isn't my script responding to mouse events like mouseenter, mouseover, or any other mouse event?

const element = document.getElementById("box"); element.addEventListener("mouseenter", handleMouse); function handleMouse(event) { console.log("Event type: " + event.type); } ...

Obtaining page information from a frame script in e10s-enabled Firefox: A guide

One of the challenges I'm facing is with my Firefox extension, where a function loads page information using the following code: var title = content.document.title; var url = content.document.location.href; However, with the implementation of multi- ...

The automated test locator in Angular using Protractor is failing to function

I am facing a challenge with my angular web application as there are some elements that are difficult to interact with. One specific element is a checkbox that needs to be checked during testing: ` <div class="row form-group approval_label"> < ...

When working with a barcode font in Chrome, using style.fontFamily may not be effective, but utilizing className can achieve the desired result

Take a look at this HTML snippet: <style> .barcode { font-family: 'BC C39 3 to 1 Medium'; } </style> <div><span id='spn'>1234567</span></div> This code will apply a barcode font style: <script> ...

The try/catch block proves ineffective at handling a socket connection exception

I am attempting to test connection to a non-existent socket. In this scenario, an exception is thrown and I anticipate it being caught in the try/catch block below. The function createConnection is imported from the net package. try { createConnection( ...

Using Javascript and Node.js to send a JSON request

While browsing through this particular question, I came across a method in node.js to distinguish between html requests and json requests: app.get('/route', function (req, res) { if (req.is('json')) res.json(data); else if (req ...