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);

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

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' }

Original: https://blog.csdn.net/seimeii/article/details/128858005
Author: 奥特慢更快
Title: ES6中扩展运算符的9种用法

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/818144/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球