What issue arises with arrays when programming in JavaScript?

Unusual scenario in JavaScript:

var array1 = new Array();
var array2 = new Array();
array1 = [[1,2],[3,4]];
for (i = 0; i < array1.length; i++) {
 array2[i] = array1[i];
}
alert(array2[1][0]); // -> 3
array1[1][0] = 10;
alert(array2[1][0]); // -> 10

I am puzzled by the unexpected behavior

Answer №1

In line 3, you create an array of arrays.

When you loop through the arrays, you are not duplicating the inner arrays, but merely creating a reference to them. This means that if you modify the contents of an inner array in arr1, it will also change the corresponding array in arr2.

There are no bugs in this code.

If you need to clone the inner arrays, you can do so using the following:

for (i=0;i<arr1.length;i++) {
 arr2[i] = arr1[i].slice(0);
}

Answer №2

Both arr1 and arr2 consist of arrays within arrays. As a result, arr2 is composed of the exact same arrays as arr1. This means that when you assign a value to an element of arr1[i], it will also reflect in the corresponding element of arr2[i] as if by magic.

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

How can I effectively refresh the provider_token / access token for Discord in NextJS with Supabase Auth?

Currently, I have encountered an issue with my NextJs project using Supabase Auth for authentication. I am currently utilizing the Discord provider and everything works fine initially. However, after a few minutes, the session object gets updated and the p ...

I am experiencing a lack of results when attempting to run db.find() in Mongodb

Recently I delved into the realm of MongoDB, deciding to create a basic application that simply showcases data stored in my database. Check out the code snippet below: var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost ...

having trouble with changing the button's background color via toggle

I've been experimenting with toggling the background color of a button, similar to how changing the margin works. For some reason, the margin toggles correctly but the button's color doesn't. <script> let myBtn = document.querySele ...

How can I dynamically insert a new HTML element into $event.target using Angular 2?

I have a webpage with a list of items. I want to display a "copy" button next to each item when the mouse hovers over it. I am currently able to create the "copy" button within the element using the following method: mouseOver(event) { if (event.tar ...

python Efficiently load zipfile data into a numpy array

I am searching for a solution to efficiently read a zipfile into memory and extract its contents into a numpy array with numpy datatypes. The challenge lies in the fact that these files are large in size and there are numerous of them, making speed a cruci ...

Using Google's Closure Compiler to Optimize JSON Files

When dealing with a json string that is parsed and properties of the object are accessed using dot notation, a warning may be triggered by the google closure compiler stating that the property is not defined. To overcome this issue, one workaround is to c ...

A guide to loading CSS and JavaScript files asynchronously

Is it possible to use loadCSS (https://github.com/filamentgroup/loadCSS/blob/master/README.md) to allow the browser to asynchronously load CSS and JavaScript? This is what I currently have in my head tag: <link rel="preload" href="http://zoidstudios. ...

"Scotchy McScotchface's to-do list application powered

How is the index.html (frontend Angular) being triggered? The tutorial mentioned that by including one of the following routes in route.js, the frontend gets called app.get('*', function(req, res) { res.sendfile('./public/index.html&ap ...

What is the appropriate method to call a function when a parameter is unnecessary?

Just to confirm, is this the correct way to call a function when a parameter is not needed? function load_img(src, alt, el, other_src) { // check if other_src exists, not null, defined, not empty, etc... } //call the function load_img(src, alt, '# ...

setInterval versus delay

I am attempting to create a div that bounces every 4 seconds, then fades out after 15 seconds. However, the current code isn't working as expected - the div disappears and the bounce effect doesn't occur. $(document).ready(function(){ functi ...

Encountering an obscure issue when using Discord.js v14 after attempting to cancel and resubmit a modal

I'm currently working on a Discord bot using modals in Discord.js v14. These modals appear after the user clicks a button, and an .awaitModalSubmit() collector is triggered to handle one modal submission interaction by applying certain logic. The .awa ...

An error occurred while trying to convert a circular data structure to JSON during an API request within another

Attempting to make an API call within another API call in this code, however encountering the following error: Error: Converting circular structure to JSON const express = require('express'); const router = express.Router(); const config = requi ...

Utilizing Node gRPC for seamless transmission of server metadata to clients without any issues

When working from the client side, adding metadata for the server is a simple process: const meta = new grpc.Metadata(); meta.add('xyz', 'okay'); stub.service.Rpc(request, meta, (err, response) => { }); To access the above on the ...

Surprising results when using react-router-dom alongside React's Context API

I am currently working on a small project where I am trying to implement basic authentication using the React Context API without Redux. Here is the code snippet: import { createContext, useContext, useState } from 'react' export const AuthConte ...

Tips for transferring JavaScript values to PHP through AjaxWould you like to learn how to

Let's set the scene. I'm currently facing a challenge in passing Javascript values to different PHP functions within my ajax code so that they can be properly displayed on the page. Here is the snippet of my code: $("[data-departmen ...

Obtain the text from an altered stylesheet in Firefox

I am currently programmatically updating stylesheets for a web page using JavaScript. My method involves having a local copy of the page and all associated assets stored on a server. After I finish making changes to the stylesheets, my goal is to save the ...

Guide on how to prevent Paste (Ctrl+V) and Copy (Ctrl+C) functionalities in a TextField within MaterialUI

Is there a way to restrict the Paste (Ctrl+V) and Copy (Ctrl+C) functions in a specific TextField within MaterialUI? I am currently working with ReactJs ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

The issue with updating the JSON data in VueJS when using draggable/sortable functionality

Hey everyone, I'm currently utilizing this library for sorting elements. I have a simple sortable setup where I'm trying to rearrange a three-element array by dragging. I can successfully change the positions, but the issue arises when my JSON ar ...

Switching from one Div to another simultaneously by sliding them out and sliding in the replacement Div

I have a situation with multiple divs within an HTML section. I'm looking for assistance in implementing a sliding effect on these div tags, either horizontally (left/right) or vertically (up/down), depending on user preference. The transition should ...