An array of size 10x10 where each new array replaces the previous one

I'm currently working on a function that generates a 10 by 10 array filled with random D's and E's. Below is the code snippet:

function generateTenByTenArray(){
    var outerArray = [];
    var innerArray = [];

    for(var i = 0; i < 10; i++){
        for(var j = 0; j < 10; j++){
            if((Math.floor(Math.random() *10) +1) % 2 == 0){
                innerArray[j] = ("D");
            } else {
                innerArray[j] = ("E");
            }
        }
        outerArray[i] = innerArray;
    }

    return outerArray;
}

However, when I run this function, I noticed that all the 10 arrays have the same values. It seems like the values in innerArray are being overwritten. Can someone explain why the new values are updating the arrays in outerArray?

If I include innerArray = [] right after outerArray[i] = innerArray, the function works as expected. I'm curious as to why this redeclaration of innerArray to an empty array fixes the issue. Does it have something to do with accessing a new memory allocation?

Thank you for your assistance in advance!

Answer №1

Two common misunderstandings lead to your confusion. The first is your use of:

outerArr[i] = arrInArr;

It appears that you believe you are assigning the value of arrInArr to outerArr[i]. However, this is not the case. You must understand that arrInArr is a pointer to an array. Therefore, the code provided simply copies a reference to arrInArr to outerArr[i]. Since there is only one arrInArr, they all point to the same array.

Secondly, you seem to think that this:

var arrInArr = [];

Is just declaring an array variable. What you may be overlooking is the code following the = sign. The above code is essentially the same as:

var arrInArr = new Array();

So, it is not just declaring a variable, but also creating an array object. This clarifies why moving it within the for loop allows the code to function properly: a new array object is created for each iteration of the loop.

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 encoding does Algolia utilize to determine the size of a JSON entry - ASCII or UTF-8?

The FAQ document from Algolia states that the maximum size of an entry should be a minified JSON size of 10KB. However, it does not specify whether the JSON string should be ASCII or UTF-8 encoded, which makes it challenging to accurately calculate the siz ...

Retrieve libraries from package-lock.json file

I am tasked with extracting all the libraries and versions from the package-lock.json file. Let me provide some context. I am implementing a security module within Jenkins to create an inventory of libraries used in each application. The goal is to gather ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Utilizing a nested Python list in JavaScript with the help of Django

On my website, I have a feature that displays data in JavaScript Array format, representing a nested list in Python. To achieve this, I utilize a JavaScript function that retrieves the data from a Django view: JavaScript function: var getDataFromFiles1 ...

What is causing the list-sorter to malfunction?

This website crashes when executed: <head> <script> var numbersList = [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 19, 17, 15, 13, 11, 9, 7, 5, 3, 1]; var orderedList = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, ...

Tips on integrating TypeScript into JavaScript

Currently, I am working with a node.js server.js file. var http = require('http'); var port = process.env.port || 1337; http.createServer(function (req, res) { res.writeHead(200, { 'Content-Type': 'text/plain' }); res ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Incorporating Meteor js into an established user system

I'm completely new to the world of Meteor and I am looking to integrate it with my current system that relies on a MongoDB database. As I explore Meteor, I have discovered that there are packages like accounts-facebook and accounts-twitter which assis ...

Customize the number of tags for React Material-UI autocomplete to only display the specified amount

I am utilizing Autocomplete in React MUI to allow for the selection of multiple options. When the Autocomplete component is out of focus, I want it to display only the tags that fit into one row. I can achieve this by using the limitTags={3} property. How ...

Ways to periodically create random values and transmit them using MQTT protocol

I need help generating and publishing unique random values to the MQTT protocol every second. Currently, my code keeps sending the same value repeatedly instead of a different one each time. How can I fix this? var mqtt = require('mqtt') var Bro ...

The operation is unable to be executed in an external document

Working on a WordPress page, I am utilizing the Google Maps API. The functions in my file are as follows: function custom_map_style() { // Enqueue Google Maps API wp_enqueue_script('maps', 'https://maps.googleapis.com/maps/api/js? ...

Having trouble transmitting JSON data to an Express server through the browser

I have set up two servers: the first one is for frontend (localhost:7200), and the second one is for backend (localhost:7300). There is a test request made by the frontend to the backend on the route '/test'. The issue arises when I attempt to s ...

How To Access a View by Clicking in Ionic Framework

I have designed the main screen shown below. When each link is clicked, it should open the corresponding view. https://i.sstatic.net/H84jt.png Here is what I have created so far: Main Screen <body ng-app="starter"> <ion-pane> < ...

Browsing an array of objects to extract targeted information

I'm in the process of developing a node express angular tool for analyzing Twitter statuses and I am facing the challenge of extracting text from it and combining it into a single long string for future use. This is how I am attempting to retrieve us ...

Tips for creating a function that outputs an array containing all the values within an object

Any help to get me through an assignment I am currently stuck on would be greatly appreciated. I am aware that the title of this post might seem confusing, so I will do my best to elaborate. Here is the assignment in question: The task is to create a func ...

Utilizing a combination of jQuery and JavaScript, construct an innovative image slider to meet

I'm working on creating a slider that allows users to navigate through reviews by clicking arrows, moving from review1 to review2 and so on. I've set up my HTML with the reviews and my CSS with hidden values for now. Any assistance would be great ...

Navigating through an array of latitude and longitude pairs during an AJAX request

Just starting out with PHP/AJAX and I could use some guidance. Currently, I have a leaflet map where I'm attempting to link two AJAX calls together. The initial AJAX call retrieves data based on a selected country ISO code. Subsequently, I've ut ...

Why is it that useEffect is functioning correctly only on the first occasion?

Recently, I've been facing significant challenges with React's useEffect and States. The issue arises when I redirect to the main page of my app and then attempt to use them again. In the following component, everything seems to function correct ...

What amount of memory is required for the largest possible array?

Is it possible to calculate the exact amount of memory required to create the largest possible array in Java? Example Program: public class MemoryOfArraysTest { public static void main(String... args) { Object[] array = new Object[Integer.MAX_ ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...