剩余参数允许我们将一个不定数量的参数表示为一个数组。
function sum (first, ...args) {
console.log(first); //10
console.log(args); // [20,30]
}
sum(10, 20, 30)
const sum = (...args) => {
let total = 0;
args.forEach(item => total += item);
return total;
}
剩余参数和解构赋值配合使用
let students = ['王五','张三','李四'];
let [s1, ...s2] = students;
console.log(s1); // '王五'
console.log(s2); // [ '张三','李四' ]
扩展运算符
扩展运算符可以将数组或者对象转为用逗号分隔的参数序列。
let ary = [1, 2, 3];
...ary // 1, 2, 3
扩展匀运算符 可以应用于合并数组
let ary1 = [1, 2, 3];
let ary2 = [4, 5, 6];
let ary3 = [...ary1, ...ary2]
// 防法2
ary1.push(...ary2);
将类数组或可遍历对象转换为真正的数组
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
var oDivs = document.getElementsByTagName('div');
console.log(oDivs)
var ary = [... oDivs];
ary.push('a');
console.log(ary)