Surprising alteration of values in a JavaScript 2D array

I am facing an issue while trying to update a single value in a 2D array. The problem seems to be related to the way the array is initialized.

The peculiar behavior occurs when I make changes to the [1][1] value in matrix while leaving matrix2 unchanged:

Matrix:

[ [ 0, 0, 0 ], [ 0, 1, 0 ], [ 0, 0, 0 ] ]

Matrix2 (unexpected):

[ [ 0, 1, 0 ], [ 0, 1, 0 ], [ 0, 1, 0 ] ]

Code:

var row = [0,0,0];
var matrix = [[0,0,0],[0,0,0],[0,0,0]];
var matrix2 = [row, row, row];
console.log(matrix);
console.log(matrix2);
matrix[1][1] = 1;
matrix2[1][1] = 1;
console.log(matrix);
console.log(matrix2);

Would appreciate insights on this puzzling situation.

Answer №1

[row, row, row]

An array with three identical references has just been created.

Modifications made to the inner array will be reflected in all references to it.

If you need three distinct copies of the inner array,
you can achieve this by making a shallow copy using .slice().

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

Leveraging Discord.JS to seamlessly transport users in Discord to their designated voice channel by assigning roles

I'm attempting to transfer all users with a specific role from a voice channel using a command like: !summon @role This command should bring only the users with that specific role to the voice channel where the command was entered My current code is ...

Incorporate new content into a jquery mobile listview on the fly

I'm attempting to use JavaScript to dynamically populate a listview with items. Here is the code I have written: //Function to load data fields for items dynamically function initialiseFields(listViewId){ for(var i = 0; i < 10; i++){ ...

Troubleshooting AngularJS: Issues arise when implementing ng-view

Here is the code snippet from my index.html file: <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1.0 ,user-scalable=no"> <sc ...

PHP - A guide to calculate the total value of a multi-level array

I need assistance with finding the total sum of values in this complex array structure: Array ( [1] => 0 [2] => 1 [3] => Array ( [0] => 1 [1] => 1 [2] => 1 ) [4] => 1 [5] => 0 ) The sum in this cas ...

Executing command prompt using Javascript

As a newcomer to stackoverflow, I am facing an issue with my asp.net web application. In one of the web forms, I need to execute cmd.exe from JavaScript on the server side after clicking a button. function onRec(){ try{ var commandtoRun = "c:\\W ...

Tips for utilizing createTextNode in JSDOM

When attempting to create a UI test for an HTML element using Jasmine and jsdom, I encountered an issue. Within my component, I utilized the createTextNode function to populate the content of the DOM element. Unfortunately, during testing, the document.c ...

Error: Unable to locate module: "./library". The parent module directory is "/"

I keep encountering an issue in my project when attempting to load a module. Whenever I try to import it from the node_modules folder, I receive the following error: Uncaught Error: Module not found: "./MyLibrary". Parent module folder was: "/" However, i ...

Selenium is encountering a maximum call stack size error while attempting to access Highcharts

This particular issue is a bit complex. My goal is to retrieve highchart data from a selenium-controlled Chrome browser using the driver.execute_script method and injecting some JavaScript: driver.execute_script("return $('#chartID').highcharts( ...

Can this be executed in PHP?

Can this code snippet work in PHP? foreach (function() { return ['key' => 'Value']; } as $key => $val){ $new_array = array('Key' => $key, 'Value' => $val); } I am interested in mo ...

jQuery Validation Engine - Error messages within a div

I'm looking to enhance my form validation using jQuery Validation Engine. I'd like to improve accessibility by displaying the error message in a tag below the input field. <input type="text" ... > <p class="error">Error message</p ...

Struggling with dragging Vue.js modals?

I am currently utilizing the vue-js-modal library, and I'm encountering an issue with it. Whenever I set my modal to be draggable by using :draggable="true", I can drag it around but then I am unable to input any text in the form fields. It seems to c ...

Exploring the Power of JQuery with Hover Effects and SlideToggle

I was struggling to keep the navbar displaying without it continuously toggling when my pointer hovered over it. I just wanted it to stay visible until I moved my pointer away. <script> $(document).ready(function(){ $(".menu-trigger").hover(funct ...

Using anchor tags to send HTML code through email

I currently have an anchor tag on my website that looks like this: <a href="mailto:<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7e0d11131b11101b3e0d11131b09161b0c1b501d1113">[email protected]</a>?subject=Wel ...

What is the best approach to comparing two arrays of strings?

What is the best way to compare the size of each word in array1 against array2 if I had two arrays of type String? String[] firstArray = {"star", "pie", "jelly bean", "car"}; STring[] secondArray = {"cookie", "fig", "banana", "soda"}; ...

Is there a way to obtain the full class name if only a portion of it is known?

I am trying to extract the complete classname of an element, but I only have partial information about it. <div class="anotherclass my-class-no-1 onemoreclass...">div> Currently, I can select the element using this: $([class*="my-class-no-"]... ...

What is the best way to paginate aggregated results in Mongoose?

In my project, I have a User model that is linked to two other associated models - Profile and WorkProfile. The Profile model contains basic information about the user like name, email, and home address, while the WorkProfile model stores details such as o ...

How can nested arrays be utilized in Angular 2 reactive forms?

After successfully using a tutorial to create reactive forms in Angular 2, I encountered a new challenge. The tutorial helped me set up an 'Organisation' form with an array of 'Contact' groups, but now I am struggling to add an array wi ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Capture the exit signal from the npm script defined in the package.json file

Is it feasible to intercept the exit signal of an npm script? "scripts": { "serve": "docker-compose up && npm start" } I am interested in implementing docker-compose down when terminating the script using ctrl+c ...

AngularJs Directive continuously returns undefined

Exploring angularjs directives for the first time has been quite a challenge. I can't seem to figure out why my directive isn't working properly as the scope.durationTimeInput always returns undefined no matter what I try. (function () { 'u ...