const arr = [1,2,3];
let arrReverse = [];
for ( let i =arr.length -1; i >=0 ; i --){
arrReverse.push(arr[i]);
}
const arrReverse2 = arr.reverse(); // 원본 배열도 순서가 뒤집힌다.
const arrReverse3 = [...arr].reverse(); // 원본배열 복사후 배열순서 바꾸기
Spread operator(스프레드 연산자, ... )
=> 배열/객체 를 펼쳐서 각 요소를 분리 후, 매개변수 목록으로 만든 다음에 매개변수를 새로운 배열/객체 에 할당함.
const arr = [1,2,3];
const obj = { a: 1, b: 2, c: 3 };
// copy
let arrayCopy2 = array.assign([], arr);
let objectCopy2 = Object.assign({}, obj);
// spread operator
const arrayCopy = [...arr] // array copy
cosnt objectCopy = {...obj} // object copy
const str = "hello"
const strStread = [...str] // ["h", "e", "l", "l", "o"]
=> 복사를 한 배열/객체 안의 요소는 원본과 같다.
=> 하지만, 원본의 값이 바뀌어도 복사된 배열/객체 의 값은 변하지 않는다. ( python 에서 copy.deepcopy 와 같음)
참고 :https://ko.javascript.info/rest-parameters-spread#spread-syntax
'프로그래밍 > JavaScript' 카테고리의 다른 글
[JS] call, apply, bind (0) | 2024.03.06 |
---|---|
객체(Object), 객체 메소드 (0) | 2023.08.03 |
array.reduce() (0) | 2023.07.30 |
Class (0) | 2023.07.13 |
Functions - arrow, map, filter (0) | 2023.07.12 |