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/