简单使用:
-
在对象中的作用
<script type="text/javascript"> let obj = { a: 1, b: 2 } let obj2 = { ...obj, b: 3 } // 修改对象中的属性值 console.log(obj2); //输出obj2{a:1,b:3} </script>
-
在数组中的作用(见个人掘金)
-
展示数组
-
连接数组
-
数组求和
-
拷贝赋值
-
修改合并
-
-
拷贝数组对象
对一维数组使用扩展运算符拷贝就属于深拷贝。严格来讲,扩展运算符不执行深拷贝?
-
合并操作
-
数组
-
对象 在合并对象时,如果一个键已经存在,它会被具有相同键的最后一个对象给替换。
-
-
参数传递
函数定义了多少个参数,扩展运算符传入的值就是多少个。
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
-
数组去重
与 Set 一起使用消除数组的重复项
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 ]
-
字符串转字符串数组
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
-
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);
-
解构赋值
-
解构数组
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' }
-
-
打印日志
在打印可迭代对象的时候,需要打印每一项可以使用扩展运算符,如下:
const years = [2018, 2019, 2020, 2021]; console.log(...years); // 2018 2019 2020 2021