1.展開運算符
能夠將對象字面量展開為多個元素
const books = ["Don Quixote", "The Hobbit", "Alice in Wonderland", "Tale of Two Cities"];
console.log(...books);
輸出:Don Quixote The Hobbit Alice in Wonderland Tale of Two Cities
還可以將數組結合
沒有...之前,使用的是concat
const fruits = ["apples", "bananas", "pears"]; const vegetables = ["corn", "potatoes", "carrots"]; const produce = fruits.concat(vegetables); console.log(produce);
輸出:["apples", "bananas", "pears", "corn", "potatoes", "carrots"]
使用...之后
const fruits = ["apples", "bananas", "pears"]; const vegetables = ["corn", "potatoes", "carrots"]; const produce = [...fruits,...vegetables]; console.log(produce);
輸出結果一樣
2.剩余參數
可以將剩余不定數的參數保存到一個數組中
const order = [20.17, 18.67, 1.50, "cheese", "eggs", "milk", "bread"]; const [total, subtotal, tax, ...items] = order; console.log(total, subtotal, tax, items);
輸出:20.17, 18.67, 1.50,["cheese", "eggs", "milk", "bread"]
3.代替argumens
對於參數不固定的函數,es6之前的處理方法是使用arguments,
function sum() { let total = 0; for(const argument of arguments) { total += argument; } return total; }
而現在直接使用剩余參數運算符就可以
function sum(...nums){ let total = 0; for(const num of nums ){ total += num; } return total; }