ES6中扩展运算符的9种用法

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' }
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

都挺好,刚刚好

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值