Why Does Changing an Array in JavaScript Affect Copies of the Array

Why does changing an Array in JavaScript affect copies of the array?

An array in JavaScript is also an object and variables only hold a reference to an object, not the object itself. Thus both variables have a reference to the same object.

Your comparison with the number example is not correct btw. You assign a new value to copyOfMyNumber. If you assign a new value to copyOfMyArray it will not change myArray either.

You can create a copy of an array using slice [docs]:

var copyOfMyArray = myArray.slice(0);

But note that this only returns a shallow copy, i.e. objects inside the array will not be cloned.

Javascript copy array. Changes affect both arrays

When you copy via .slice or [...] it performs a shallow copy, which means the outer array is copied but the inner arrays aren't. You can individually copy each element:

let ans = board.map(v => v.slice()); // copies every 1d array

Why is the y-array changing when I modify the x array? javascript

Copying value by reference. - https://www.dyn-web.com/javascript/arrays/value-vs-reference.php

What you want to do instead -

let x = [7,2];

let y = [...x];

x[0] = 9;

(2) [9, 2]

y
(2) [7, 2]

Why making changes to copy of array , affects to original array?

The spread operator creates a shallow copy. If the content of a menu was objects, then changing those objects in a copy array will change those objects in the original array (or technically, those two references are for the same object):

const obj1 = {
val: 1
}

const obj2 = {
val: 2
}

const obj3 = {
val: 3
}

const arr = [obj1, obj2, obj3]

// creating a copy with the spread operator
const copy = [...arr]

// changing the second element in the copy
copy[1].val = 22

// the element in the original array is changed too
console.log(arr)

Why does changing one array alters the other?

Because "a" and "b" reference the same array. There aren't two of them; assigning the value of "a" to "b" assigns the reference to the array, not a copy of the array.

When you assign numbers, you're dealing with primitive types. Even on a Number instance there's no method to update the value.

You can see the same "they're pointing to the same object" behavior with Date instances:

var d1 = new Date(), d2 = d1;
d1.setMonth(11); d1.setDate(25);
alert(d2.toString()); // alerts Christmas day

A copy of an array changes the original array even with slice

You aren't changing the array, you are mutating the objects within the array. You don't want that.

const myObj = {
x:1,
y:1
};

const myArray = [myObj];
const myNewArray = [...myArray];

myNewArray[0].x = 2;
console.log(myArray[0].x); // 2!!!!!

If you are changing an object within the array and you don't want it to mutate, then do this:

const myObj = {
x:1,
y:1
};

const myArray = [myObj];

// helper function that will perform a mutation at a given position
// and ignore all other positions
const mutateObjectAtPosition = (pos,mutation) => [...myArray].map((o,i) => i === pos ? mutation(o) : o)

// at position 0, return a **new object** with x set to 2
const myNewArray = mutateObjectAtPosition(0,(o) => ({...o,x:2}));

console.log(myNewArray !== myArray); // true, different references
console.log(myNewArray[0].x); // 2
console.log(myArray[0].x); // 1

Change the value of an array changes original array JavaScript

Yes. Both valueArray and labelArray reference the same underlying array. To make a copy, use slice():

valueArray = labelArray.slice(0);

NOTE: Slice() only copies 1 level deep, which works fine for primitive arrays. If the array contains complex objects, use something like jQuery's clone(), credit @Jonathan.

Why changing array variables item affects the array it has been inserted to in Javascript?

Objects in javascript (like arrays) are passed around as references. So, when you do:

a.push(b)

You are pushing a reference to b into the array a. If you later change b, there is only one b so it will change in all places that refer to it, including in the array.

Another way to say this is that a.push(b) does not make a copy of b. What was pushed into the array just points to the same b you've always had so if you change b, the reference in the array just points to the one b there is so looking at the value through the array will see the change too.


If you truly want a copy (that won't be affected by changes to the original) pushed into the array, you can make an explicit copy using .slice().

var a = [1,2,3];
var b = [5,4];
var c = 6;
a.push(b.slice()); // push a shallow copy of b

This is a fairly fundamental thing to grasp when learning javascript. When you pass or assign objects in javascript (and an array is one type of object), a copy is not made. Instead, you end up with more than one part of your code all pointing to the exact same object. This is obviously a feature that can be taken advantage of, but it means that when you want an independent copy that has no connection to the original, you have to explicitly make a copy.

To contrast with this, primitives such as Boolean or Number are assigned or passed as a copy.

why this arrays changes its value itself?

Try this. Reference is made here

<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function arrayClone( arr ) {

var i, copy;

if( Array.isArray( arr ) ) {
copy = arr.slice( 0 );
for( i = 0; i < copy.length; i++ ) {
copy[ i ] = arrayClone( 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=arrayClone(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>




Related Topics



Leave a reply



Submit