数组的展开运算符的基本使用
- 认识展开运算符
//要求,求出arr数组中的最小值 const arr = [2, 4, 6, 7]; //我们知道在js中Math对象中有一个min方法 Math.min(2, 4, 6, 7);//min方法可以求出列表中最小的数字 //那么这里就需要将 [2, 4, 6, 7]===>2, 4, 6, 7 然后运用min方法求出最小值 // …arr 就可以将数组展开成一个 数字列表 Math.min(…arr); console.log(Math.min(…arr)); - 数组展开运算符的基本用法 console.log(…[2, 4, 5]);
区分剩余参数和展开运算符 - 根本区别
展开运算符:[1,3,5]->1,3,5 将数组装换为数字列表 剩余参数:2,3,5 ->[2,3,5] 将数字列表转换为数组 - 区分剩余参数和展开运算符例子
const add = (…args) => {//…args 剩余参数 console.log(…args);//…args 展开剩余参数args里面的内容 //[a,b,c,…args]=[1,3,4,5,6,7] } add(1,2,3,4,5);//1 2 3 4 5 const arr = […[2, 3, 5], 34, 7, 56];//…[2,3,5] 展开运算符 console.log(arr);//新的数组 [2, 3, 5, 34, 7, 56]
数组展开运算符的应用
1.复制数组
const a = [2, 3, 4, 5];
const b = a;// a与b指向的同一个地址
const c = […a];//c为一个新的数组
console.log(a === c);//false
2.合并数组
const a = [2, 3, 4, 5]; const b = [2, 3, 5, 7]; const c = […a, …b];//合并之后的新数组 console.log©;// [2, 3, 4, 5, 2, 3, 5, 7] - 字符串转为数组
字符串可以按照数组的形式展开 - 常见的类数组转换为数组
// arguments NodeList function func() { // arguments 类数组 console.log(arguments);// // args 数组 const args = […arguments]; console.log(args);//[23, 45, 6] } func(23, 45, 6); - 对象的展开运算符
对象展开运算符的基本用法 - 展开对象 对象不能直接的展开,必须写在{}中 对象的展开:把属性罗列出来,用逗号分隔,放到一个{}对象,构成一个新的对象
const person = { name: ‘zhangsan’, sex: ‘male’, age: 34 } console.log({ …person });//展开以后是一个新的对象 console.log({ …person } === person);//false - 合并对象
const person = { name: ‘zhangsan’, sex: ‘male’, age: 34 } const boss = { name: ‘wangwu’, sex: ‘male’, age: 40, emp: ‘xiaohong’ } // 新的对象拥有全部属性,相同属性后者覆盖前者 const people = { …person, …boss }; console.log(people); //{name: ‘wangwu’, sex: ‘male’, age: 40, emp: ‘xiaohong’}
对象展开符的注意事项 - 空对象的展开 如果展开一个空对象,则没有任何效果
console.log({…{}}); - 非对象的展开
如果展开的不是对象,则会自动将其转为对象,再将其属性罗列出来
console.log({ …1 });//空对象 console.log({ …false });//空对象 console.log({ …undefined });//空对象 console.log({ …‘helloworld’ });//得到一个对象 //如果展开运算符后面的是字符串,她会自动转成一个类数组的对象,因此返回的不是空对象 - 对象中的对象属性的展开,不会展开对象中的对象属性
const boss = { name: ‘laoma’, age: 34, emp: { name: ‘xiaohong’, age: 21 } } const boss1 = { name: ‘laoma’, age: 34, emp: { name: ‘xiaoming’, sex: ‘male’, address: ‘广州’ } } console.log({ …boss }); // 相同的属性值 后面的覆盖前面的 console.log({ …boss, …boss1 });
对象展开运算符的应用
1.复制对象
const a = { x: 1, y: 2 } const b = a;// const c = { …a }; console.log(c, c === a);//false - 用户参数与默认参数
const logUser = ({ name = ‘zhangsan’, age = 0 } = {}) => { console.log(name, age)
} logUser(); const logUser = userParam => { const defaultPar = { name: ‘zhangsan’, age: 23, sex: ‘male’ } // 用户传递过来的参数与默认参数进行合并 // 得到最终的参数 // const param={…defaultPar,…userParam}; // console.log(param); const { name, age, sex } = { …defaultPar, …userParam }; console.log(name, age, sex); } logUser({ name: ‘xiaohong’, sex: ‘female’ });