【ES6.0】- 扩展运算符(...)

简介: 笔记

一、概述


**扩展运算符(...)**允许一个表达式在期望多个参数(用于函数调用)或多个元素(用于数字字面量)或多个变量(用于解构赋值)的位置扩展。扩展运算符是ES6中引入的,将可迭代对象展开到其单独的元素中,所谓的可迭代对象就是任何能用for of循环进行遍历的对象。如:数组(数组常用方法)、字符串、Map、Set、DOM节点等。


二、拷贝数组对象


使用扩展符拷贝数组是ES6中常用的操作:

const arr_01=[100,200,300,400,'hello']
let arr_02 = [...arr_01]
let arr_03 = arr_01
arr_02.push('E01','E02')
console.log(arr_02)  //[100,200,300,400,'hello','E01','E02']
console.log(arr_01)  //[100,200,300,400,'hello']
arr_03.push('C01')
console.log(arr_01)  //[100,200,300,400,'hello','C01']

扩展运算符拷贝数组,只有第一层是深拷贝,既对一维数组使用扩展符拷贝就属于深拷贝。


三、合并操作


合并对象,在合并对象时,如果一个键已经存在,它会被具有相同键的最后一个对象给替换。

const halfMonths1 = [101,102,103,104]
const halfMonths2 = [201,202,203,204]
const halfMonths3 = [...halfMonths1,...halfMonths2] //[101,102,103,104,201,202,203,204]
console.log(halfMonths3)


四、参数传递


const sum = (num1,num2)=>num1+num2
console.log(sum(16,17)) //13
console.log(sum(...[16,17])) //13
console.log(sum(...[16,17,18])) //13

从上面的代码看,函数定义了多少个参数,扩展运算符传入的值就是多少个


五、数组去重


const param = ['a','b','c','b','b','c']
const param_01 = [...new Set(param)]
console.log(param_01) //['a','b','c']

与Set一起使用消除数组的重复项。


六、字符串转字符数组


String也是一个可迭代对象,所以也可以使用扩展运算符... 将其转为字符数组。

const title = 'goyeer'
const arr_title = [...title]
console.log(arr_title)

进而可以简单进行字符串截取。


const title = 'goyeer'
const arr_title = [...title]
arr_title.length = 2
console.log(arr_title.join("")) //go


七、NodeList转数组


NodeList对象是节点的集合,通常是由属性和方法返回的


NodeList类似于数组,但不是数组,没有Array的所有方法如:find 、map、filter等,但是可以使用 forEach()来迭代。

const nodelist = document.querySelectorAll(".row")
const nodeArray = [...nodelist]
console.log(nodelist)
console.log(nodeArray)


八、解构变量


解构数组,下面演示:

const [first,second,...others] = [100,101,102,103,104]
console.log(first)
console.log(second)
console.log(others)


解构对象,如:

const userInfo = {name:"goyeer",province:"jiangsu",city:"suzhou"}
const {name,..loaction} = userinfo
console.log(name)  //goyeer
console.log(location) //{province:"jiangsu",city:"suzhou"}


九、打印日志


在打印可迭代对象的时候,需要打印每一项可以使用扩展符:

const years = [2018,2019,2020,2021]
console.log(...years) //2018,2019,2020,2021


十、总结


扩展运算符...让代码变的简洁,而且是ES6中非常使用受欢迎的内容

目录
打赏
0
0
0
0
41
分享
相关文章
利用ES6中的...扩展运算符来合并数组
本文介绍了使用ES6的新特性简化JavaScript编程的多种方法。其中包括使用扩展运算符`...`优雅地合并数组,解构赋值快速提取数组和对象值,`for...of`循环及箭头函数提升数组遍历效率,`find`方法简化数组搜索,`+`号与短路运算符优化数据类型转换及默认值设置,以及模板字符串和扩展运算符增强的对象合并技巧,这些方法让代码更加简洁高效。
66 0
es6 扩展运算符
【8月更文挑战第20天】
47 0
|
6月前
|
ES6新增语法 扩展运算符
ES6新增语法 扩展运算符
35 0
AI助理

你好,我是AI助理

可以解答问题、推荐解决方案等