解構 - 三個點運算子
阿新 • • 發佈:2021-08-05
1.陣列-拆分
const arr =[1,2,3,4,5,6,7] const [a,b,...c] = arr console.log(a,b,c)
2.陣列-合併
const a = [1,2,3],b = [4,5,6] const c = [...a,...b] console.log(c)
3.字串-轉陣列
const [...arr] = 'string'
4.類陣列-轉陣列
const [...div] = document.getElementsByTagName('div')
5.實現迭代器介面的資料
const obj = { *[Symbol.iterator](){ yield1 yield 2 yield 3 yield 4 yield 8 } } console.log([...obj])
6.物件解構
let {name,age,...other} = {name:'zhangsan',age:18,job:'前端開發',province:'深圳'}
console.log(name,age,other)
7....賦值語句
const obj = {a:1,b:2} const o = {a:8,c:13,...obj} const obj1 = {a:12,b:23} const obj= {c:89,d:99} const newobj = {...obj1,...obj2}
8.使用表示式
const isTrue = true const obj = {...(isTrue? obj1:obj2),c:33}
9.三點(...)賦值解構陣列,會隱式呼叫其object方法
console.log({...[1,2,3]})
console.log({...'string'})
10.函式使用:... 獲取剩餘引數
function demo(a,b,...params){ console.log(params) } demo(1,2,3,4,5,6)
11.將陣列傳遞給引數
function demo(...args){ console.log(args) } const arr = [2,3,4,5] demo.apply(null,arr) demo(...arr)
12.其它
不能解構 null 和undefined
結構是淺複製
... 無法解構原型屬性,屬性解構是可以的