持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第22天,点击查看活动详情
1. 数组扩展运算符
扩展运算符(spread)是将一个数组转为用逗号分隔的参数序列,与 rest 参数的逻辑相反。(写法为...)
简单理解: 数组 => 参数序列
// 拆解数组
const array = [1,2,3];
console.log(...array);//1 2 3
// 函数调用
function addArr(array, ...items) {
array.push(...items);
return array;
}
const items = [7, 8, 9];
addArr(array, ...items); // [1, 2, 3, 7, 8, 9]
2. 对象扩展运算符
对象的扩展运算符用于拷贝目标对象的所有可遍历属性到当前对象之中。(写法为...)
对象的扩展运算符等同于使用Object.assign()方法,实现对象复制或者合并。(Object.assign()方法的相关知识可以查看这篇文章《【JavaScript基础】浅析对象Object》)。
let person = {name: '阿尼亚', age: 7};
let newPerson = {...person};
console.log(newPerson) // {name: '阿尼亚', age: 7}
const a = { name: 'a' , father: 'A' }
let aClone = { ...a };
// 等同于
let aClone = Object.assign({}, a);
console.log(aClone) //{name: 'a', father: 'A'}
3. 扩展运算符的应用
a. 替代函数的 apply() 方法
扩展运算符和Math.max()方法,求数组最大值
// Math.max()函数返回一组数中的最大值
// apply()方法将数组转换为函数参数
Math.max.apply(null, [1, 2, 3])
//扩展运算符将数组[1, 2, 3]的解构为一组数值1,2,3
Math.max(...[1, 2, 3])
b. 复制数组、拷贝对象
//复制数组(克隆一个全新的数组,比如修改a2不会影响a1)
const a1 = [1, 2];
const a2 = [...a1]; // [1, 2]
//拷贝对象(同样为克隆一个全新的对象)
const obj = {
name:"jym",
age: 7 ,
}
const obj2 = {...obj};
console.log(obj2); // {name: 'jym', age: 7}
c. 合并数组、对象
const a1 = [1, 2];
const a2 = ['hello','world'];
const a3 = [...a1, ...a2]; //[1, 2, 'hello', 'world']
const o1 = { foo: 1 };
const o2 = { bar: 2 };
const o3 = {...o1, ...o2}; //{foo: 1, bar: 2}
4. 函数的rest参数
rest参数用于获取函数的多余参数,可以替代arguments对象。(写法为...变量名)
简单理解: 参数序列 => 数组
- rest参数获取的多余参数组成数组,而
arguments对象是一个类似数组的对象,不能使用数组方法,需要先通过Array.from()转换为数组
// arguments变量的写法
// 报错
// function sortNumbers() {
// return arguments.push(3);
// }
// sortNumbers(1,2) //Uncaught TypeError: arguments.push is not a function
function sortNumbers() {
let newArray = Array.from(arguments)
newArray.push(3)
return newArray;
}
sortNumbers(1,2) // [1,2,3]
// rest参数的写法
const sortNumbers = (...numbers) => {
numbers.push(4);
return numbers;
//下面的写法会返回数组长度length,因为push()方法添加元素到数组末尾,并返回新长度length,会改变数组自身
//return numbers.push(4)
};
sortNumbers(1,2) // [1,2,4]
- rest参数可称为剩余参数,即rest参数必须是参数列表的最后一个,如果rest参数后面还有其他参数,则会报错
// 编辑器里报错:A rest parameter must be last in a parameter list.
function f(a, ...b, c) {}
5. rest参数的应用
a. 与解构赋值结合使用,定义数组变量
const [first, ...rest] = [1, 2, 7];
first // 1
rest // [2, 7]
b. 代替arguments变量