JavaScript ⑅ES6:展开运算子 & 其余运算子

展开运算子及 其余运算子( 又称 其余参数 )
他们有共通特点,那就是「 都跟阵列有关 」
 
写法就是 ...
没错,就是 「 ... 」( 写在文字编辑器中应该是会变色 )
 
 

⑅ 展开运算子 (spread operator)

啊到底是要展开什么,这个东西很妙,他可以各种展开。
直接看例子:

let a = ['阿喵', 'kent', 'Ben'];let b = ['水母', '蛋花', '汤'];let c = [...a , ...b];console.log(c) //['阿喵', 'kent', 'Ben', '水母', '蛋花', '汤']

WTF
居然 ... 就让他们合体了 什么巫术?

仔细的看一下

console.log(...a) // '阿喵', 'kent', 'Ben'console.log(...b) // '水母', '蛋花', '汤'

原来就是 concat 啊
关于 concat 的用法这边 ( 推销自己文章 )
 


⑅ 浅拷贝

没有在骂髒话

大家都知道 JS 有深拷贝 跟 浅拷贝
如果阵列or 物件 他们有一样的参考位置的话,修改其中一样、另外一样也会跟着被更动到。

let a = ['阿喵', 'kent', 'Ben'];let b = a ;b[0] = '秀柱';console.log(a) // ['秀柱', 'kent', 'Ben']

夭寿,我不是改b 吗? 为什么 a 会被改到啊?
这就是因为他们有一样的参考位置 的关係。

在讲这个 ... 会提到浅拷贝,
其实是因为 ... 可以解决这样的问题 。

如下:

let a = ['阿喵', 'kent', 'Ben'];let b = [...a] ;b[0] = '秀柱';console.log(a) // ['阿喵', 'kent', 'Ben']

... 好像真的很方便!!
 


⑅ 类阵列 却不是阵列?

JS 有很多 看起来跟阵列就是99.9987% 像但却不能用阵列操作法的东东
称他们为 类阵列

像是这种:

<!-- HTML --><li class='item'> 123 </li><li class='item cat'> 123 </li><li class='item'> 123 </li>
const item = document.querySelectorAll('.item')console.log(item)// NodeList(3) [li.item, li.item.cat, li.item]const item1 = item.filter( i =>   i.classList.contains('cat'))// Uncaught TypeError: list_a.filter is not a function 

这种NodeList 就是类阵列。

使用展开运算子 居然能让他变成 阵列

const item = [...document.querySelectorAll('.item')]console.log (item) // [li.item, li.item.cat, li.item]const item1 = item.filter( i =>  i.classList.contains('cat'))console.log(item1)// [li.item.cat]

 


⑅ 其余运算子(rest operator)

就很字面上的意思,其余参数。

他会放在函式的参数括号内,然后记得他必须放最后一个,否则会跳错。

这个参数也可以用阵列操作法去操作( forEach 、map 之类的 )

function fn(...a){  console.log(a)    let num = a.filter(i=>i>3)  console.log(num)// [4, 5, 6]}fn(1,2,3,4,5,6)

再来「如果有多个参数,他要放最后面」的範例:

function fn(x,y,...a){  console.log(`参数 x 是 ${x}`)// 参数 x 是 1  console.log(`参数 y 是 ${y}`)// 参数 y 是 2  console.log(`参数 ...a 是 ${a}`)// 参数 ...a 是 3, 4, 5, 6}fn(1,2,3,4,5,6) 

 


⑅ 物件 + 展开 = 这太懒了吧

如 title (
这边直接看 code 会比较好懂:

const cat_mother = {    mother_name: '喵仔',    mother_age: 2,    mother_color: 'yellow'}const cat_father = {    father_name: '喵吉',    father_age: 55,    father_color: 'Rainbow'}const cat = {    name: '阿猫',    age: 10,    color: 'pink',...cat_mother, //展开猫妈妈...cat_father //展开猫爸爸}console.log(cat) /* Object {      age: 10,      color: "pink",      father_age: 55,      father_color: "Rainbow",      father_name: "喵吉",      mother_age: 2,      mother_color: "yellow",      mother_name: "喵仔",      name: "阿猫" }*/

 
 
ES6 真的懒 ww
以后看到 ... 就不会错愕哩 ꉂꉂ(ᵔᗜᵔ*)

じゃあねー ♫


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章