如何在JavaScript中克隆數組

JavaScript has many ways to do anything. I’ve written on 10 Ways to Write pipe/compose in JavaScript, and now we’re doing arrays.

JavaScript有許多方法可以執行任何操作。 我已經寫了10種用JavaScript編寫管道/組合的方法 ,現在我們正在做數組。

1.傳播算子(淺副本) (1. Spread Operator (Shallow copy))

Ever since ES6 dropped, this has been the most popular method. It’s a brief syntax and you’ll find it incredibly useful when using libraries like React and Redux.

自從ES6刪除以來,這一直是最受歡迎的方法。 這是一個簡短的語法,在使用像React和Redux這樣的庫時,您會發現它非常有用。

numbers = [1, 2, 3];
numbersCopy = [...numbers];

Note: This doesn’t safely copy multi-dimensional arrays. Array/object values are copied by reference instead of by value.

注意:這不能安全地復制多維數組。 數組/對象值是通過引用而不是value復制的。

This is fine

這可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

這樣不好

nestedNumbers = [[1], [2]];
numbersCopy = [...nestedNumbers];numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

2. Good Old for()循環(淺副本) (2. Good Old for() Loop (Shallow copy))

I imagine this approach is the least popular, given how trendy functional programming’s become in our circles.

我想這種方式是流行的,時髦給出函數式編程在我們的圈子怎么成了。

Pure or impure, declarative or imperative, it gets the job done!

純凈或不純凈,陳述性或命令性,就可以完成工作!

numbers = [1, 2, 3];
numbersCopy = [];for (i = 0; i < numbers.length; i++) {numbersCopy[i] = numbers[i];
}

Note: This doesn’t safely copy multi-dimensional arrays. Since you’re using the = operator, it’ll assign objects/arrays by reference instead of by value.

注意:這不能安全地復制多維數組。 由于使用的是=運算符,它將按引用而不是按分配對象/數組。

This is fine

這可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

這樣不好

nestedNumbers = [[1], [2]];
numbersCopy = [];for (i = 0; i < nestedNumbers.length; i++) {numbersCopy[i] = nestedNumbers[i];
}numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

3. Good Old while()循環(淺副本) (3. Good Old while() Loop (Shallow copy))

Same as for—impure, imperative, blah, blah, blah…it works! ?

for -impure,勢在必行,等等,等等,等等...它的作品! ?

numbers = [1, 2, 3];
numbersCopy = [];
i = -1;while (++i < numbers.length) {numbersCopy[i] = numbers[i];
}

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是value分配對象/數組。

This is fine

這可以

numbersCopy.push(4);
console.log(numbers, numbersCopy);
// [1, 2, 3] and [1, 2, 3, 4]
// numbers is left alone

This is not fine

這樣不好

nestedNumbers = [[1], [2]];
numbersCopy = [];i = -1;while (++i < nestedNumbers.length) {numbersCopy[i] = nestedNumbers[i];
}numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1, 300], [2]]
// [[1, 300], [2]]
// They've both been changed because they share references

4. Array.map(淺副本) (4. Array.map (Shallow copy))

Back in modern territory, we’ll find the map function. Rooted in mathematics, map is the concept of transforming a set into another type of set, while preserving structure.

回到現代領域,我們將找到map函數。 map 起源于數學 ,它是在保留結構的同時將集合轉換為另一種類型的集合的概念。

In English, that means Array.map returns an array of the same length every single time.

用英語來說,這意味著Array.map返回相同長度的數組。

To double a list of numbers, use map with a double function.

要將數字列表加倍,請使用帶有double函數的map

numbers = [1, 2, 3];
double = (x) => x * 2;numbers.map(double);

克隆呢? (What about cloning??)

True, this article’s about cloning arrays. To duplicate an array, just return the element in your map call.

沒錯,本文是關于克隆數組的。 要復制數組,只需在map調用中返回元素即可。

numbers = [1, 2, 3];
numbersCopy = numbers.map((x) => x);

If you’d like to be a bit more mathematical, (x) => x is called identity. It returns whatever parameter it’s been given.

如果您想更加數學化, (x) => x稱為identity 。 它返回給定的任何參數。

map(identity) clones a list.

map(identity)克隆一個列表。

identity = (x) => x;
numbers.map(identity);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是通過value分配對象/數組。

5. Array.filter(淺拷貝) (5. Array.filter (Shallow copy))

This function returns an array, just like map, but it’s not guaranteed to be the same length.

該函數返回一個數組,就像map一樣,但是不能保證長度相同。

What if you’re filtering for even numbers?

如果您要過濾偶數數怎么辦?

[1, 2, 3].filter((x) => x % 2 === 0);
// [2]

The input array length was 3, but the resulting length is 1.

輸入數組的長度為3,但結果長度為1。

If your filter's predicate always returns true, however, you get a duplicate!

如果您的filter的謂詞始終返回true ,那么您將得到一個重復項!

numbers = [1, 2, 3];
numbersCopy = numbers.filter(() => true);

Every element passes the test, so it gets returned.

每個元素均通過測試,因此將其返回。

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是value分配對象/數組。

6. Array.reduce(淺副本) (6. Array.reduce (Shallow copy))

I almost feel bad using reduce to clone an array, because it’s so much more powerful than that. But here we go…

使用reduce克隆數組幾乎讓我感到難過,因為它的功能要強大得多。 但是,我們開始…

numbers = [1, 2, 3];numbersCopy = numbers.reduce((newArray, element) => {newArray.push(element);return newArray;
}, []);

reduce transforms an initial value as it loops through a list.

當它循環遍歷列表時, reduce轉換初始值。

Here the initial value is an empty array, and we’re filling it with each element as we go. That array must be returned from the function to be used in the next iteration.

這里的初始值是一個空數組,我們將在每個元素中填充它。 該數組必須從函數中返回,以在下一次迭代中使用。

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是value分配對象/數組。

7. Array.slice(淺拷貝) (7. Array.slice (Shallow copy))

slice returns a shallow copy of an array based on the provided start/end index you provide.

slice根據您提供的開始/結束索引返回數組的淺表副本。

If we want the first 3 elements:

如果我們想要前三個元素:

[1, 2, 3, 4, 5].slice(0, 3);
// [1, 2, 3]
// Starts at index 0, stops at index 3

If we want all the elements, don’t give any parameters

如果我們需要所有元素,請不要提供任何參數

numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5]

Note: This is a shallow copy, so it also assigns objects/arrays by reference instead of by value.

注意:這是一個淺表副本,因此它也按引用而不是按分配對象/數組。

8. JSON.parse和JSON.stringify(深復制) (8. JSON.parse and JSON.stringify (Deep copy))

JSON.stringify turns an object into a string.

JSON.stringify將對象轉換為字符串。

JSON.parse turns a string into an object.

JSON.parse將字符串轉換為對象。

Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.

將它們組合在一起可以將一個對象變成一個字符串,然后逆轉該過程以創建一個全新的數據結構。

Note: This one safely copies deeply nested objects/arrays!

注意:此 安全復制深層嵌套的對象/數組

nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);// [[1], [2]]
// [[1, 300], [2]]
// These two arrays are completely separate!

9. Array.concat(淺副本) (9. Array.concat (Shallow copy))

concat combines arrays with values or other arrays.

concat將數組與值或其他數組組合。

[1, 2, 3].concat(4); // [1, 2, 3, 4]
[1, 2, 3].concat([4, 5]); // [1, 2, 3, 4, 5]

If you give nothing or an empty array, a shallow copy’s returned.

如果不提供任何內容或提供空數組,則返回淺表副本。

[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是value分配對象/數組。

10. Array.from(淺副本) (10. Array.from (Shallow copy))

This can turn any iterable object into an array. Giving an array returns a shallow copy.

這可以將任何可迭代對象轉換為數組。 提供數組將返回淺表副本。

numbers = [1, 2, 3];
numbersCopy = Array.from(numbers);
// [1, 2, 3]

Note: This also assigns objects/arrays by reference instead of by value.

注意:這還會通過引用而不是通過value分配對象/數組。

結論 (Conclusion)

Well, this was fun ?

好吧,這很有趣嗎?

I tried to clone using just 1 step. You’ll find many more ways if you employ multiple methods and techniques.

我嘗試僅用1個步驟進行克隆。 如果您采用多種方法和技術,則會發現更多方法。

翻譯自: https://www.freecodecamp.org/news/how-to-clone-an-array-in-javascript-1d3183468f6a/

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391628.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391628.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391628.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

leetcode 227. 基本計算器 II(棧)

給你一個字符串表達式 s &#xff0c;請你實現一個基本計算器來計算并返回它的值。 整數除法僅保留整數部分。 示例 1&#xff1a; 輸入&#xff1a;s “32*2” 輸出&#xff1a;7 解題思路 利用兩個棧&#xff0c;一個記錄操作數&#xff0c;一個記錄操作符&#xff0c;…

100米隊伍,從隊伍后到前_我們的隊伍

100米隊伍,從隊伍后到前The last twelve months have brought us a presidential impeachment trial, the coronavirus pandemic, sweeping racial justice protests triggered by the death of George Floyd, and a critical presidential election. News coverage of these e…

idea使用 git 撤銷commit

2019獨角獸企業重金招聘Python工程師標準>>> 填寫commit的id 就可以取消這一次的commit 轉載于:https://my.oschina.net/u/3559695/blog/1596669

ES6標準入門(第二版)pdf

下載地址&#xff1a;網盤下載 內容簡介 ES6&#xff08;又名 ES2105&#xff09;是 JavaScript 語言的新標準&#xff0c;2015 年 6 月正式發布后&#xff0c;得到了迅速推廣&#xff0c;是目前業界超級活躍的計算機語言。《ES6標準入門&#xff08;第2版&#xff09;》…

hexo博客添加暗色模式_我如何向網站添加暗模式

hexo博客添加暗色模式同一個網站&#xff0c;兩種不同的配色方案 (Same website, two different color schemes) Last year I made it a point to redesign my website from scratch. I wanted something simple and minimalist looking that clearly stated what this was — …

leetcode 331. 驗證二叉樹的前序序列化

序列化二叉樹的一種方法是使用前序遍歷。當我們遇到一個非空節點時&#xff0c;我們可以記錄下這個節點的值。如果它是一個空節點&#xff0c;我們可以使用一個標記值記錄&#xff0c;例如 #。_9_/ \3 2/ \ / \4 1 # 6 / \ / \ / \ # # # # # # 例如&#xff0…

mongodb數據可視化_使用MongoDB實時可視化開放數據

mongodb數據可視化Using Python to connect to Taiwan Government PM2.5 open data API, and schedule to update data in real time to MongoDB — Part 2使用Python連接到臺灣政府PM2.5開放數據API&#xff0c;并計劃將數據實時更新到MongoDB —第2部分 目標 (Goal) This ti…

4.kafka的安裝部署

為了安裝過程對一些參數的理解&#xff0c;我先在這里提一下kafka一些重點概念,topic,broker,producer,consumer,message,partition,依賴于zookeeper, kafka是一種消息隊列,他的服務端是由若干個broker組成的&#xff0c;broker會向zookeeper&#xff0c;producer生成者對應一個…

javascript初學者_針對JavaScript初學者的調試技巧和竅門

javascript初學者by Priyanka Garg由Priyanka Garg My intended audience for this tutorial is beginner programmers. You’ll learn about frustration-free debugging with chrome dev tools.本教程的目標讀者是初學者。 您將學習使用chrome開發工具進行無挫折的調試。 D…

leetcode 705. 設計哈希集合

不使用任何內建的哈希表庫設計一個哈希集合&#xff08;HashSet&#xff09;。 實現 MyHashSet 類&#xff1a; void add(key) 向哈希集合中插入值 key 。 bool contains(key) 返回哈希集合中是否存在這個值 key 。 void remove(key) 將給定值 key 從哈希集合中刪除。如果哈希…

ecshop 前臺個人中心修改側邊欄 和 側邊欄顯示不全 或 導航現實不全

怎么給個人中心側邊欄加項或者減項 在模板文件default/user_menu.lbi 文件里添加或者修改,一般看到頁面都會知道怎么加,怎么刪,這里就不啰嗦了 添加一個欄目以后,這個地址跳的頁面怎么寫 這是最基本的一個包括左側個人信息,頭部導航欄 <!DOCTYPE html PUBLIC "-//W3C//…

leetcode 706. 設計哈希映射

不使用任何內建的哈希表庫設計一個哈希映射&#xff08;HashMap&#xff09;。 實現 MyHashMap 類&#xff1a; MyHashMap() 用空映射初始化對象 void put(int key, int value) 向 HashMap 插入一個鍵值對 (key, value) 。如果 key 已經存在于映射中&#xff0c;則更新其對應…

數據庫語言 數據查詢_使用這種簡單的查詢語言開始查詢數據

數據庫語言 數據查詢Working with data is becoming an increasingly important skill in the modern workplace. 在現代工作場所中&#xff0c;處理數據已成為越來越重要的技能。 Data is no longer the domain of analysts and software engineers. With todays technology,…

面向對象編程思想-觀察者模式

一、引言 相信猿友都大大小小經歷過一些面試&#xff0c;其中有道經典題目&#xff0c;場景是貓咪叫了一聲&#xff0c;老鼠跑了&#xff0c;主人被驚醒&#xff08;設計有擴展性的可加分&#xff09;。對于初學者來說&#xff0c;可能一臉懵逼&#xff0c;這啥跟啥啊是&#x…

typescript 使用_如何使用TypeScript輕松修改Minecraft

typescript 使用by Josh Wulf通過喬什沃爾夫(Josh Wulf) 如何使用TypeScript輕松修改Minecraft (How to modify Minecraft the easy way with TypeScript) Usually, modifying Minecraft requires coding in Java, and a lot of scaffolding. Now you can write and share Min…

Python:在Pandas數據框中查找缺失值

How to find Missing values in a data frame using Python/Pandas如何使用Python / Pandas查找數據框中的缺失值 介紹&#xff1a; (Introduction:) When you start working on any data science project the data you are provided is never clean. One of the most common …

監督學習-回歸分析

一、數學建模概述 監督學習&#xff1a;通過已有的訓練樣本進行訓練得到一個最優模型&#xff0c;再利用這個模型將所有的輸入映射為相應的輸出。監督學習根據輸出數據又分為回歸問題&#xff08;regression&#xff09;和分類問題&#xff08;classfication&#xff09;&#…

leetcode 54. 螺旋矩陣(遞歸)

給你一個 m 行 n 列的矩陣 matrix &#xff0c;請按照 順時針螺旋順序 &#xff0c;返回矩陣中的所有元素。 示例 1&#xff1a; 輸入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 輸出&#xff1a;[1,2,3,6,9,8,7,4,5] 示例 2&#xff1a; 輸入&#xff1a;matrix [[1,…

微服務架構技能

2019獨角獸企業重金招聘Python工程師標準>>> 微服務架構技能 博客分類&#xff1a; 架構 &#xff08;StuQ 微服務技能圖譜&#xff09; 2課程簡介 本課程分為基礎篇和高級篇兩部分&#xff0c;旨在通過完整的案例&#xff0c;呈現微服務的開發、測試、構建、部署、…

phpstorm 調試_PhpStorm中的多用戶調試

phpstorm 調試by Ray Naldo雷納爾多(Ray Naldo) PhpStorm中的多用戶調試 (Multi-User Debugging in PhpStorm) 使用Xdebug和DBGp代理 (Using Xdebug and DBGp Proxy) “Er, wait a minute… Don’t you just use xdebug.remote_connect_back which has been introduced since …