ES6中扩展运算符的9种用法
阿里云国内75折 回扣 微信号:monov8 |
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6 |
1. 拷贝数组对象
const years = [2018, 2019, 2020, 2021];
const copyYears = [...years];
console.log(copyYears); // [ 2018, 2019, 2020, 2021 ]
扩展运算符拷贝数组只有第一层是深拷贝即对一维数组使用扩展运算符拷贝就属于深拷贝
2. 合并数组
先来看数组的合并如下
const halfMonths1 = [1, 2, 3, 4, 5, 6];
const halfMonths2 = [7, 8, 9, 10, 11, 12];
const allMonths = [...halfMonths1, ...halfMonths2];
console.log(allMonths); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
3.合并对象
合并对象在合并对象时如果一个键已经存在它会被具有相同键的最后一个对象给替换。
const time1 = {
month: 7,
day: {
value: 1,
},
};
const time2 = {
year: 2021,
month: 8,
day: {
value: 10,
},
};
const time = { ...time1, ...time2 };
console.log(time); // { month: 8, day: { value: 10 }, year: 2021 }
4.参数传递
const sum = (num1, num2) => num1 + num2;
console.log(sum(...[6, 7])); // 13
console.log(sum(...[6, 7, 8])); // 13
从上面的代码看函数定义了多少个参数扩展运算符传入的值就是多少个。
和 math 函数一起使用如下
const arrayNumbers = [1, 5, 9, 3, 5, 7, 10];
const min = Math.min(...arrayNumbers);
const max = Math.max(...arrayNumbers);
console.log(min); // 1
console.log(max); // 10
5.数组去重
const arrayNumbers = [1, 5, 9, 3, 5, 7, 10, 4, 5, 2, 5];
const newNumbers = [...new Set(arrayNumbers)];
console.log(newNumbers); // [ 1, 5, 9, 3, 7, 10, 4, 2 ]
6.字符串转字符数组
String 也是一个可迭代对象所以也可以使用扩展运算符 … 将其转为字符数组如下
const title = "china";
const charts = [...title];
console.log(charts); // [ 'c', 'h', 'i', 'n', 'a' ]
进而可以简单进行字符串截取如下
const title = "china";
const short = [...title];
short.length = 2;
console.log(short.join("")); // ch
7.NodeList 转数组
NodeList 对象是节点的集合通常是由属性如 Node.childNodes 和方法如 document.querySelectorAll 返回的。
NodeList 类似于数组但不是数组没有 Array 的所有方法例如find、map、filter 等但是可以使用 forEach() 来迭代。
可以通过扩展运算符将其转为数组如下
const nodeList = document.querySelectorAll(".row");
const nodeArray = [...nodeList];
console.log(nodeList);
console.log(nodeArray);
8.解构变量
解构数组如下
const [currentMonth, ...others] = [7, 8, 9, 10, 11, 12];
console.log(currentMonth); // 7
console.log(others); // [ 8, 9, 10, 11, 12 ]
解构对象如下
const userInfo = { name: "Crayon", province: "Guangdong", city: "Shenzhen" };
const { name, ...location } = userInfo;
console.log(name); // Crayon
console.log(location); // { province: 'Guangdong', city: 'Shenzhen' }