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; }