자바 스크립트는 무엇이든 할 수있는 다양한 방법을 가지고 있습니다. 저는 자바 스크립트에서 파이프 / 컴 포즈를 작성하는 10 가지 방법에 대해 작성했으며 이제 우리는 배열을 수행하고 있습니다.
1. 스프레드 연산자 (얕은 카피)
ES6가 떨어진 이후로 이것은 가장 인기있는 방법이었습니다. 간단한 구문이며 React 및 Redux와 같은 라이브러리를 사용할 때 매우 유용하다는 것을 알게 될 것입니다.
numbers = [1, 2, 3]; numbersCopy = [...numbers];
참고 : 이것은 다차원 배열을 안전하게 복사하지 않습니다. 어레이 / 객체 값으로 복사 된 기준 대신하여 값 .
이건 괜찮아
numbersCopy.push(4); console.log(numbers, numbersCopy); // [1, 2, 3] and [1, 2, 3, 4] // numbers is left alone
이건 좋지 않아
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. 좋은 오래된 for () 루프 (얕은 복사)
나는이 접근 방식이 우리 서클에서 유행하는 함수형 프로그래밍이 얼마나 인기가 있는지를 고려할 때 가장 덜 인기 가 있다고 생각합니다 .
순수하거나 불순하거나 선언적이거나 명령 적이든, 작업이 완료됩니다!
numbers = [1, 2, 3]; numbersCopy = []; for (i = 0; i < numbers.length; i++) { numbersCopy[i] = numbers[i]; }
참고 : 이것은 다차원 배열을 안전하게 복사하지 않습니다. =
연산자를 사용하기 때문에 value 대신 참조로 객체 / 배열을 할당합니다 .
이건 괜찮아
numbersCopy.push(4); console.log(numbers, numbersCopy); // [1, 2, 3] and [1, 2, 3, 4] // numbers is left alone
이건 좋지 않아
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. 좋은 오래된 while () 루프 (얕은 복사)
" for
순수, 명령, 어쩌구, 어쩌구, 어쩌구… ?
numbers = [1, 2, 3]; numbersCopy = []; i = -1; while (++i < numbers.length) { numbersCopy[i] = numbers[i]; }
참고 : 이것은 또한 값 대신 참조로 객체 / 배열을 할당합니다 .
이건 괜찮아
numbersCopy.push(4); console.log(numbers, numbersCopy); // [1, 2, 3] and [1, 2, 3, 4] // numbers is left alone
이건 좋지 않아
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 (얕은 복사)
현대 영토로 돌아가서 우리는 그 map
기능을 찾을 것 입니다. 수학에 뿌리를 둔 것은 map
구조를 유지하면서 집합을 다른 유형의 집합으로 변환하는 개념입니다.
영어에서는 Array.map
매번 같은 길이의 배열을 반환 한다는 의미 입니다.
숫자 목록을 두 배로 늘리려면 함수 map
와 함께 사용하십시오 double
.
numbers = [1, 2, 3]; double = (x) => x * 2; numbers.map(double);
복제는 어떻습니까 ??
사실,이 기사는 어레이 복제에 관한 것입니다. 배열을 복제하려면 map
호출 에서 요소를 반환하면 됩니다.
numbers = [1, 2, 3]; numbersCopy = numbers.map((x) => x);
좀 더 수학적으로되고 싶다면 그것을 identity(x) => x
라고 합니다. 주어진 매개 변수를 반환합니다.
map(identity)
목록을 복제합니다.
identity = (x) => x; numbers.map(identity); // [1, 2, 3]
참고 : 이것은 또한 값 대신 참조로 객체 / 배열을 할당합니다 .
5. Array.filter (얕은 복사)
이 함수는와 같이 배열을 반환 map
하지만 길이가 같지 않을 수도 있습니다.
짝수를 필터링한다면 어떨까요?
[1, 2, 3].filter((x) => x % 2 === 0); // [2]
입력 배열 길이는 3이지만 결과 길이는 1입니다.
If your filter
's predicate always returns true
, however, you get a duplicate!
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.
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…
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.
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.
7. Array.slice (Shallow copy)
slice
returns a shallow copy of an array based on the provided start/end index you provide.
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 and JSON.stringify (Deep copy)
JSON.stringify
turns an object into a string.
JSON.parse
turns a string into an object.
Combining them can turn an object into a string, and then reverse the process to create a brand new data structure.
Note: This onesafely 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 (Shallow copy)
concat
combines arrays with values or other arrays.
[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.
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.
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.