在JavaScript中,三个点“…”实际上是什么[duplicate]

问题描述 投票:0回答:1

我已经看过以下javascript代码:

 let num = [1,2,2,2,3,4,5];
 console.log([... new Set(nums)]); //which prints [1,2,3,4,5]

我不明白在这个例子中……(三个点)是什么?有帮助吗?

javascript ecmascript-6 syntax
1个回答
0
投票

我认为您需要先阅读Iteration

let nums = [1,2,2,2,3,4,5];
let setFromArray = new Set(nums);
let arrayFromSet_spread = [...setFromArray];
console.log("spread", arrayFromSet_spread);
 
// here the spread will iterate over iteratable and return current value

//arrayFromSet can be written without spread like this
let arrayFromSet_forOf = [];
for ( let el of setFromArray ) {
  arrayFromSet_forOf.push(el)
}
console.log("forOf",arrayFromSet_forOf);


// and the most naive way to iterate :)
let arrayFromSet_ManualIteration = [];
let setFromArrayIterator = setFromArray[Symbol.iterator]();
const firstElement = setFromArrayIterator.next();
const secondElement = setFromArrayIterator.next();
const thirdElement = setFromArrayIterator.next();
const fourthElement = setFromArrayIterator.next();
const fifthElement = setFromArrayIterator.next();
const sixthElement = setFromArrayIterator.next();

arrayFromSet_ManualIteration.push(firstElement);
arrayFromSet_ManualIteration.push(secondElement);
arrayFromSet_ManualIteration.push(thirdElement);
arrayFromSet_ManualIteration.push(fourthElement);
arrayFromSet_ManualIteration.push(fifthElement);
arrayFromSet_ManualIteration.push(sixthElement);

//you could just push values not the itaration object itself
//arrayFromSet_ManualIteration.push(firstElement.value);
//arrayFromSet_ManualIteration.push(secondElement.value);
//arrayFromSet_ManualIteration.push(thirdElement.value);
//arrayFromSet_ManualIteration.push(fourthElement.value);
//arrayFromSet_ManualIteration.push(fifthElement.value);

console.log('ManualIteration full objects',arrayFromSet_ManualIteration);
© www.soinside.com 2019 - 2024. All rights reserved.