简体   繁体   中英

What is the need to copy, or slice, an array vs. creating a variable that is just equal to existing one?

let a = {"foo": 99};
let b = a;
// console.log(b)  {"foo": 99}

a.foo = 33;
// console.log(b)  {"foo": 33}

I understand in the scenario above that if I use objects, the variable referencing the original object will reflect the value of the original object.

But if I do this with arrays:

let a = [1,2,3];
let b = a;

a = [99,99,99];
// console.log(b) [1,2,3];

variable b still references the original value of a even after a changed so then what would the person of creating a copy via slice() serve?

This is because, by doing a = [99, 99, 99] , you are creating an entirely new object, and "resetting" a . But when doing a.foo = 33 , you are modifying an existing object and references to it.

You can see that when I set a[0] instead of a , b still equals a :

 let a = [1, 2, 3]; let b = a; a[0] = [99, 99, 99]; console.log(b);

When using the slice() method, b retains a 's original value.

Example:

 let a = [1, 2, 3]; let b = a; a = a.slice(2); console.log(a, b);

JavaScript is a loosely typed language, which means that you don't have to specify what type of data will be stored in a variable in advance.

In your case, you have selected let a=[1,2,3]; which gets overridden later. but let suppose you had something like the below.

let a = [{name: 'David'}, {name: 'Tim'}];
let b = a;
b[0].name = 'Bruce';
console.log(a[0].name); //Bruce

In the aforementioned example, you see that the array assignment to a different variable won't help you retain the actual value in your original array. Hence, it's always better to copy the array instead of just assigning it to another variable if it needs modification.

In addition, when copying it is always better to do a deep copy to avoid missing information.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM