Modifying a single variable will impact all other variables that are defined in a similar manner

I'm facing an issue with my JavaScript code. I have 4 three-dimensional arrays, each of size 500x500x220. To optimize performance, I defined a single array and then created the other four arrays from it. However, when I modify one array, it affects the others as well. Here is how my code looks:

<script type="text/javascript">
var content = new Array();
var signs = new Array();
var sens = new Array();
var props = new Array();
var ini = new Array();
for(i = 0; i < 500; i++){
        ini[i] = new Array();
        for(j = 0; j < 500; j++){
                    ini[i][j] = new Array();
        }
}
content = ini;
signs = ini;
sens = ini;
props = ini;
function f(){
        alert(signs[3][3][2]);            //Returns undefined
        content[3][3][2] = 2;
        alert(signs[3][3][2]);            //Returns 2
}
f();
</script>

Even though the f() function is meant to only modify the content array, it ends up affecting the signs array as well. Can anyone explain why this happens and suggest a workaround?

Just so you know, I am using HTA.

Answer №1

After reading an informative post on Stack Overflow regarding copying nested arrays, a new method was discovered.

The original code snippet:

content = ini;
signs = ini;
sens = ini;
props = ini;

simply made all the arrays point to ini, resulting in cross-references between them.

It is recommended to use the following function instead:

function copy(arr){
    var new_arr = arr.slice(0);
    for(var i = new_arr.length; i--;)
        if(new_arr[i] instanceof Array)
            new_arr[i] = copy(new_arr[i]);
    return new_arr;
}

This function allows you to properly copy the arrays like so:

content = copy(ini);
signs = copy(ini);
sens = copy(ini);
props = copy(ini);

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

JavaScript allows for accessing form values easily

I am facing an issue with retrieving form values using JavaScript. Below is the HTML code for the form: <form action="./ExampleServlet" method="POST" id="myform"> <label>Username</label> <input type="text" name="user">< ...

Encountering a runtime error in React while making an async call on a NextJS 13 page

I am currently working on implementing async calls using the new app layout in NextJS 13. I have been referring to the latest documentation page. However, I have encountered an error that I can't seem to resolve. https://i.sstatic.net/CpNmu.png Belo ...

Node.js population process

Hello, I am currently exploring Node.js and facing an issue with the populate() method. My goal is to populate the user model with forms. Here is the structure of the model: const UserSchema = new Schema({ firstName: { type: 'string&a ...

Creating a table with React components to display an object

I'm a React novice struggling to render an object in a table. While I can access the ctx object using console.log, I can't seem to display it in the table on the browser. Any help and advice would be greatly appreciated. The code snippet is provi ...

Ways to display divs by moving the mouse across the entire screen, rather than just over the specific element

I successfully implemented functionality to hide and show my classes when the user hovers over a specific element. However, what I really want is for these classes to show up when the user moves their mouse anywhere on the screen, not limited to just the s ...

Obtain access to global.window.localStorage within getServerSideProps

I have a component that receives props with data and renders the data. In my functionality within the getServerSideProps, I am attempting to retrieve data from localStorage. However, due to window being undefined, I am unable to do so. I have tried using ...

Exploring the mocking of document,hidden using Jasmine

Struggling to simulate document.hidden in an angular unit test, but facing issues. Tried the following solutions: spyOn(Document.prototype, <any>'hidden').and.returnValue(true); spyOn(Document, <any>'hidden').and.ret ...

What is the best way to handle passing the "img" object to an onload event handler in ReactJS JSX?

I am currently working on an img element that I want to be able to listen for the onLoad event. However, I also need access to the image object itself in order to check properties like width and height. Since these images are generated dynamically, I won&a ...

"Exploring the Relationship Between Pointers and Arrays in the C Programming

While I wouldn't call myself an expert in the C language, I thought I had a good understanding of pointers until I encountered two different implementations that supposedly produce the same result. I can't seem to wrap my head around it. Can some ...

Merge two arrays where one array is larger in size

Dealing with arrays can be tricky, especially when trying to merge a smaller array B into a larger array A. In this case, the process involves ensuring that the values from array B are appended to array A without overwriting any existing data. However, the ...

Show dropdown menu on bootstrap responsive table

I've encountered an issue with a bootstrap3 responsive table that includes dropdown selections in each row. When the dropdown is clicked, users have to scroll to view all the options, especially on smaller screens where scrolling becomes impossible. ...

Retrieve the decimal separator and other locale details from the $locale service

After reviewing the angular $locale documentation, I noticed that it only provides an id (in the form of languageId-countryId). It would be helpful to have access to more specific information such as the decimal separator character. Is there a way to retri ...

Leveraging express functions in Node.js framework

Currently, I am delving into the world of nodeJS and have stumbled upon a great collection of tutorials. The tutorials are focused on teaching me about a powerful framework known as express. In order to utilize express effectively, one must also grasp the ...

implement CSS styles within a JavaScript function

I am trying to change the background every second with the following code, but I am having trouble including CSS properties like centering, covering, and positioning the image properly. How can I modify this function to incorporate these settings for the ...

Tips for displaying icons in a row when hovering my mouse

I'm trying to incorporate feather icons into my project, specifically the trash icon to appear next to the item name when I hover over it. I found someone else asking a similar question on Stacks, but unfortunately, they didn't receive an answer ...

Javascript prototype plugin designed to loop through images

Looking for recommendations on a JavaScript plugin that can rotate small images on a card. Check out for an example of the desired functionality. Preferably looking for a Prototype implementation, but JQuery could also work if needed. Curious to explor ...

Display a checkbox and automatically mark it as checked if a value from one dataset is found in another dataset

I am trying to check whether a value exists from one dataset to another dataset. Specifically, I want to utilize the id property for this purpose. I have been experimenting with handlebars.js, but the code below is not functioning properly. Here is the s ...

Utilizing AngularJS and RequireJS for intricate routing within web applications

I have encountered an issue with nested routings that I am struggling to resolve. The technologies I am using include: AngularJS, RequireJS; AngularAMD, Angular Route. To start off, here is my main routing setup: app.config(function($routeProvider, $loc ...

What is the reasoning behind AngularJS 2 HTTP Post only allowing string data as input?

Can someone explain to me why the HTTP Post method in AngularJS 2 (2.0.0-beta.13) only accepts string data as body, unlike in AngularJS 1 where it can accept a JavaScript object? AngularJS-1: $http.post(someUrl,someObject) AngularJS-2: http.post(someUr ...

Use two fingers to scroll up and down on the screen

I am currently developing a sketch web application (using angular) that utilizes one finger gestures for drawing. My goal is to enable vertical scrolling in the sketch content by using two fingers. However, when attempting to scroll with two fingers, Safa ...