What is causing this array to automatically alter its value?

How can I prevent A from changing its value when I only want to modify Q in the first loop of this html/javascript code?

  • Why does A change even though I am only changing Q?
  • What steps can I take to avoid A from changing?

<!DOCTYPE html>
<html>
<body>


<p id="demo"></p>

<script>
var A=[[3,4],[5,7]];

var Q=[];

 for (var k=0;k<2;k++){
 
    Q= A;

    for (var i=0;i<2;i++) {
        Q[k][i]=1;
                    
       }
  }
document.getElementById("demo").innerHTML =  A;

</script>

</body>
</html>

Answer №1

Check out this solution for cloning a nested array in JavaScript here

<!DOCTYPE html>
<html>
<body>
  <p id="demo"></p>
  <script>
     function cloneArray( arr ) {
     
         var i, copy;
     
         if( Array.isArray( arr ) ) {
             copy = arr.slice( 0 );
             for( i = 0; i < copy.length; i++ ) {
                 copy[ i ] = cloneArray( copy[ i ] );
             }
             return copy;
         } else if( typeof arr === 'object' ) {
             throw 'Cannot clone array containing an object!';
         } else {
             return arr;
         }
     
     }
     
     A=[[3,4],[5,7]];
     var Q=cloneArray(A);
     
      for (var k=0;k<2;k++){
         for (var i=0;i<2;i++) {
             Q[k][i]=1;
                         
            }
       }
     
     document.getElementById("demo").innerHTML =  A;
     
  </script>

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

Using three.js to establish an Image for Particle

I am looking to make some changes to this demo: Instead of having colored particles, I want to assign an image to each one. Should I use a cube for this purpose? Or is there a way to use an image with Vector3? Here is the code for the example: i ...

Closing the React Material UI drawer with nested list items upon clickingORClicking on nested list

Currently, I am encountering an issue with my React project that utilizes Material-UI. The problem arises when I incorporate nested list items within the drawer component. Previously, everything was functioning smoothly until the addition of these nested i ...

What is the best way to create a border for the active class nav-item in Bootstrap 4?

I am facing an issue with changing styles in the nav-item. I have created a separate style sheet and added the necessary code to make the changes. Surprisingly, the changes are reflecting well in Internet Explorer but not in Firefox. Can anyone guide me on ...

Material-UI's JSS does not adhere to the justify content property

Having trouble aligning elements in my React app using material-ui 1.0 and its JSS solutions. The code I've written below should center justify, but it's not working no matter how I configure it. I suspect there might be a naming issue since mat ...

What is the method for submitting a form when a change occurs?

This inquiry is focused on the Captive Network Assistant. I attempted to utilize plain JavaScript, <form action=""> <select name="test" onchange="this.form.submit()"> <option value="1">1</option> <option val ...

Boost Page Text Size Using CSS

Possible Duplicate: Allowing users to adjust font size on a webpage My goal is to create webpages where users can click an image to increase the font size of all content. Is this achievable? If so, how would I go about implementing it? I am aware that ...

Using Custom .woff Format Fonts in Sendgrid: A Guide

Having trouble with implementing custom fonts in Sendgrid. While Google fonts work fine, the custom .woff format font doesn't seem to cooperate. I've attempted three solutions below. Solution number 1 shows up in the Preview tab but not in the em ...

Obtain image data from a websocket server built in C# or VB.NET

Just starting out in the world of websockets, I've got a handle on the client-side code (JavaScript makes it easy) But diving into the websocket server side, particularly in c#, is a whole different ballgame. I'm in need of websocket server code ...

The compatibility issue between Angular JS variables and Twig is causing functionality problems

issue Currently, I am utilizing a combination of Twig templates and AngularJS. controller public function testAction() { $this->render('AcmeDemoBundle:abc.html.twig'); } javascript code var scotchApp = angular.module('scotch ...

What is the best way to implement an IF THEN ELSE statement using ngStyle in Angular?

How can I make rows in a table highlight based on the STATUS value? Currently, I have it set up to show yellow if the STATUS is 1 using the following code: [ngStyle]="{'background-color': cnresult.STATUS === 1 ? 'yellow' : '&a ...

Encountering a 500 error with Ajax in Laravel 5.2

Rediscovering Laravel 5.2 - Starting a Fresh Application After getting back into Laravel, I encountered a challenge with an AJAX post request. Essentially, when you reorder the list, AJAX is triggered to modify the order and save it in the database. Desp ...

What is the best way to retrieve the targeted style directly from CSS, rather than relying on the computed style of the element?

Although similar questions have been posed before, such as this one, I haven't found a working solution. Is there a way for me to retrieve the width attribute value from a CSS class and then write it to a div? I'm looking to access the exact va ...

How to retrieve the query string in VueJS

Recently, I've delved into the world of VueJS and so far, it's been a great experience! :) One thing I'm trying to figure out is how to save querystring values to a VueJS variable. It seems like a straightforward task in handlebars + express ...

Wrapping an <h1> tag inside an <a> link can create unwanted empty space on a web page

I am currently in the process of rebuilding the Porsche website using HTML, CSS, and JS. Specifically, I am looking to implement a "build your Porsche" link by enclosing it within an anchor tag. However, this seems to be causing excessive spacing on the pa ...

Querying specific data from the API using unique identifiers

If the api.football-data.org/v1/competitions holds this data: { "_links": { "teams": { "href": "http://api.football-data.org/v1/competitions/444/teams" } }, "id": 444, "caption": "Campeonato Brasileiro da Série A", ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

Two child DIVs within a single parent DIV

I am struggling to keep two divs side-by-side within a parent div. Initially, I was able to position the image in the right div successfully, but when resizing the elements, everything became disorganized and I can't seem to fix it. As a beginner, I w ...

What is the best way to retrieve the values of a select element from LEVEL 4 within the form submission of LEVEL 3?

To enhance readability, the intricate code has been abstracted. Within our Angular 2 project, we are working with a component called <top-component> (LEVEL 1): <top-component> </top-component> This component includes a template known a ...

Using jQuery to parse JSON transforms an array into a hash object

I recently encountered an issue with a string that I needed to convert into a JSON object. The string looked like this: string = '{ "key": [ { "foo": "bar" } ] }'; To convert the string, I used: json = $.parseJSON(string); However, after co ...

Authenticate the user by comparing the entered username and password with the database records. If they match, proceed to redirect the user to their profile page. Otherwise, log

Attempting to complete this assignment which involves a user entering their username and password. If the information matches what is stored in the database, the user should be redirected to their profile page where a personalized greeting message is displ ...