*它可與陣列和物件一起使用,在陣列中,它的使用時間為:
1。 建構數組
2. 將參數傳遞給函數
1- 建立陣列:
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
如您所見,擴充運算子使事情變得更加容易。
如果您再次想要擴充陣列的各個元素,請使用擴充運算子:
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
const foods = ['chicken', 'meat', 'rice']; const Newfoods = [...foods, 'pizza ']; console.log(Newfoods); // ['chicken', 'meat', 'rice', 'pizza ']
console.log(foods); // ['chicken', 'meat', 'rice']
擴充運算子與陣列的兩個有用用例:
1.建立陣列的副本:
const arrOriginal = [1, 2, 3, 4, 5]; const arrCopy = [...arrOriginal]; console.log(arrCopy); // [1, 2, 3, 4, 5]
2.合併兩個或多個陣列:
const arr1 = ['A', 'B', 'C']; const arr2 = ['D', 'E', 'F']; const mergedArr = [...arr1, ...arr2]; console.log(mergedArr); // ['A', 'B', 'C', 'D', 'E', 'F']
const str = 'spongeBob'; const letters = [...str, 'squarePants']; console.log(letters); // ['s', 'p', 'o', 'n', 'g', 'e', 'B', 'o', 'b', 'squarePants']
console.log(`spelling sponge bob's name: ${...str}`); // Expression expected
2- 將參數傳遞給函數
const arr = [5, 6, 7]; // without the spread operator ? const badArr = [1, 2, 3, 4, arr[0], arr[1], arr[2]]; console.log(badArr); // [1, 2, 3, 4, 5, 6, 7] // with the spread operator ? const goodArr = [1, 2, 3, 4, ...arr]; console.log(goodArr); // [1, 2, 3, 4, 5, 6, 7]
console.log(...goodArr); // 1 2 3 4 5 6 7 //the line above is just like writing this code: console.log(1, 2, 3, 4, 5, 6, 7); // 1 2 3 4 5 6 7
希望您能理解這裡的所有內容,如果您有任何疑問,請隨時在評論部分提問,感謝您的閱讀?
以上是JavaScript 擴充運算符的詳細內容。更多資訊請關注PHP中文網其他相關文章!