Modifying a copy of a javascript array is causing the original array to change

Cloning objects -

A loop / array.push produces a similar result to array.slice[0] or array.clone[]. Values are all passed by reference, but since most primitive data types are immutable, subsequent operations produce the desired result - a 'clone'. This is not true of objects and arrays, of course, which allow for modification of the original reference [they are mutable types].

Take the following example:

const originalArray = [1, 'a', false, {foor: 'bar'}]
const newArray = [];

originalArray.forEach[[v, i] => {
    newArray.push[originalArray[i]];
}];

newArray[0] = newArray[0] + 1;
newArray[1] = 'b';
newArray[2] = true;
newArray[3] = Object.assign[newArray[3], {bar: 'foo'}];

The operations run on the newArray indices all produce the desired result, except the final [object], which, because it is copied by reference, will mutate the originalArray[3] as well.

//jsfiddle.net/7ajz2m6w/

Note that array.slice[0] and array.clone[] suffers from this same limitation.

One way to solve this is by effectively cloning the object during the push sequence:

originalArray.forEach[[v, i] => {
    const val = [typeof v === 'object'] ? Object.assign[{}, v] : v;
    newArray.push[val];
}];

//jsfiddle.net/e5hmnjp0/

cheers

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.
but why?

What I have tried:

var func= new function [] {
         var A = [20, 30, 25, 5, 3, 2];
         var B = A;

         for [var i = 0; i  A[i+1]] {
                 var tmp = A[i];
                 A[i] = A[i + 1];
                 A[i + 1] = tmp;
             }
         }

             var big = A[A.length-1];
             var index = 0;

             for [var j = 0; j 

Chủ Đề