擴展運算符(…)用於取出參數對象中的所有可遍歷屬性,拷貝到當前對象之中
let bar = { a: 1, b: 2 }; let baz = { ...bar }; // { a: 1, b: 2 }
參考:https://blog.csdn.net/astonishqft/article/details/82899965
應用:
1、將數組轉化為函數參數序列
function add(x, y) { return x + y; } const numbers = [4, 38]; add(...numbers) // 42
2、對數組進行值拷貝(直接用=是無法對數組進行值拷貝的,只能復制一份引用)
const arr1 = [1, 2];
const arr2 = [...arr1];
3、字符串轉為字符數組
[...'hello'] // [ "h", "e", "l", "l", "o" ]
4、迭代器iterator接口轉為數組
5、數組合成
first // 1
rest // [2, 3, 4, 5]
const [first, ...rest] = [1, 2, 3, 4, 5]; 需要注意的一點是: 如果將擴展運算符用於數組賦值,只能放在參數的最后一位,否則會報錯。 const [...rest, last] = [1, 2, 3, 4, 5]; // 報錯 const [first, ...rest, last] = [1, 2, 3, 4, 5]; // 報錯