How to Clone an Array in Javascript?
- 时间:2020-09-17 14:26:24
- 分类:网络文摘
- 阅读:90 次
In Javascript, the arrays are passed by reference, and sometimes we want to clone an array. We cannot use the simple = operator as the reference is assigned.
1 2 3 4 | var arr = [1, 2, 3]; var newArray = arr; // true, as they both point to the same memory location console.log(arr === newArray); |
var arr = [1, 2, 3]; var newArray = arr; // true, as they both point to the same memory location console.log(arr === newArray);
We can also use Array.from, the ES6 syntax sugar – triple dot spreader …, or the old fashion way .slice() to return a new copy of the array. Let’s see the following examples.
1 2 3 4 5 6 7 8 9 10 11 12 13 | var arr = [1, 2, 3, 4]; var newArr0 = arr; var newArr1 = arr.slice(); var newArr2 = [...arr]; var newArr3 = Array.from(arr); // true console.log(arr === newArr0); // all below are showing false as new arrays are cloned console.log(arr === newArr1); console.log(arr === newArr2); console.log(arr === newArr3); |
var arr = [1, 2, 3, 4]; var newArr0 = arr; var newArr1 = arr.slice(); var newArr2 = [...arr]; var newArr3 = Array.from(arr); // true console.log(arr === newArr0); // all below are showing false as new arrays are cloned console.log(arr === newArr1); console.log(arr === newArr2); console.log(arr === newArr3);
Is that it? How about multidimensional arrays? Are the above methods supposed to do their jobs?
1 2 3 4 5 6 7 8 9 10 11 12 13 | var arr = [[1, 2], [3, 4]]; var newArr1 = arr.slice(); var newArr2 = [...arr]; var newArr3 = Array.from(arr); newArr1[0][0] = 'a'; console.log(arr[0][0]); // prints a newArr2[0][0] = 'b'; console.log(arr[0][0]); // prints b newArr3[0][0] = 'c'; console.log(arr[0][0]); // prints c |
var arr = [[1, 2], [3, 4]]; var newArr1 = arr.slice(); var newArr2 = [...arr]; var newArr3 = Array.from(arr); newArr1[0][0] = 'a'; console.log(arr[0][0]); // prints a newArr2[0][0] = 'b'; console.log(arr[0][0]); // prints b newArr3[0][0] = 'c'; console.log(arr[0][0]); // prints c
It turns out that all the above methods are providing the shallow copies – where only the first dimensions are copied by values and the subsequent dimensions are still copying the references. Therefore, if you change the values in the above 2 dimensional ‘cloned’ arrays, the original arrays are impacted even those three ‘cloned’ arrays are of different memory locations!
The deep clone (or deep copy) in Javascript, can be done via a custom deep copy function, as detailed in: How to Clone Variables (The Clone Function) in Javascript?
–EOF (The Ultimate Computing & Technology Blog) —
推荐阅读:揭秘减肥食品菇类营养价值抗癌降血脂 冬季感冒多喝姜茶可治疗外感风寒感冒 消除身体疲劳可多吃七种带“香”的食物 饮食与健康:维生素B2的补充无需刻意 女性急躁易发怒可能与维生素缺乏有关系 冬天吃水果,究竟应该注意什么问题? 萝卜的保健功能和萝卜的食疗吃法 红枣美味营养可养生但是禁忌亦不少 不同包装的牛奶,你知道该如何选择吗 冬天吃羊肉如何去掉羊膻味及饮食禁忌
- 评论列表
-
- 添加评论