ES6 노트 - 연산자 확장

9600 단어
연산자 펼치기 (세 개의 연속점 (... 로 표시) 는 ES6의 새로운 개념으로 글씨체의 대상을 여러 요소로 펼칠 수 있다.
우리는 몇 가지 예시를 통해 그것의 원리를 보았다.
const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);

Prints: Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities
const primes = new Set([2, 3, 5, 7, 11, 13, 17, 19, 23, 29]);
console.log(...primes);

Prints: 2 3 5 7 11 13 17 19 23 29
상기 예시된 출력을 보면, 그룹과 집합이 하나의 요소로 확장된 것을 발견할 수 있습니다.이게 무슨 소용이야?
참고: 컬렉션은 ES6에 새로 내장된 객체입니다.앞으로 ES6 3교시에서 컬렉션을 자세히 살펴보겠습니다.

concat 방법으로 그룹 결합


연산자를 펼치는 용도는 결합수조이다.
만약 여러 개의 그룹을 결합해야 한다면, 연산자를 펼치기 전에, Array concat() 방법을 사용해야 한다.
const fruits = ["apples", "bananas", "pears"];
const vegetables = ["corn", "potatoes", "carrots"];
const produce = fruits.concat(vegetables);
console.log(produce);

Prints: ["apples", "bananas", "pears", "corn", "potatoes", "carrots"]
그다지 나쁘지는 않지만, 약자 방법이 있다면 더 좋지 않을까요?
예를 들면 다음과 같습니다.

⚠️ 다음에 const 경고가 나옵니다.⚠️


코드를 복사하거나 붙여넣는 것을 통해 따라가면 const 키워드로 produce 변수를 설명했습니다.다음 코드는 변수를 다시 설명하고 값을 다시 부여하려고 시도할 것입니다. 따라서 코드를 실행하는 방식에 따라 오류가 발생할 수 있습니다.const 성명을 사용하는 변수는 같은 작용 영역에서 다시 성명하거나 값을 부여할 수 없습니다.
const produce = [fruits, vegetables];
console.log(produce);

Prints: [Array[3], Array[3]]
유감스럽게도 안 된다.
이 코드는 실제적으로 fruits수조를 produce수조의 첫 번째 인덱스에 추가하고 vegetables수조를 두 번째 인덱스에 추가합니다.
연산자 확장을 시도해 볼까요?
const fruits = ["apples", "bananas", "pears"];
const vegetables = ["corn", "potatoes", "carrots"];
const produce = [...fruits, ...vegetables];
console.log(produce);

좋은 웹페이지 즐겨찾기