ES6?拓展運(yùn)算符(...)

// 拓展運(yùn)算符(...)

var arr = [1,2,3]


// 1、...arr 返回?cái)?shù)組的各個(gè)值

console.log(...arr)? // 1 2 3

console.log([...arr])? // [1,2,3]

function text1(x,y,z){

? console.log(x)? // 1

? console.log(y)? // 2

? console.log(z)? // 3

}

text1(...arr)




// 2、拷貝數(shù)組對(duì)象

// 在這里你會(huì)發(fā)現(xiàn),這是一個(gè)深拷貝,其實(shí)不然,展開(kāi)語(yǔ)法和 Object.assign() 行為一致, 執(zhí)行的都是淺拷貝(只遍歷一層)。


// 數(shù)組

var arr2 = [...arr]

console.log(arr2)? // [1,2,3]

console.log(arr === arr2)? // false


// 對(duì)象

var obj = {

? a: 1,

? b: 2

}

var obj2 = {...obj}

console.log(obj2)? // {a: 1,b: 2}

console.log(obj === obj2)? // false




// 3、構(gòu)造字面量數(shù)組對(duì)象


// 數(shù)組

var arr3 = [...arr, ...arr2]

console.log(arr3)? // [1,2,3,1,2,3]


// 對(duì)象

// 當(dāng)key值相同時(shí),會(huì)被覆蓋

var obj3 = {...obj, ...obj2}

console.log(obj3)? // {a: 1,b: 2}

// 當(dāng)key值相同時(shí),后一個(gè)會(huì)覆蓋前一個(gè)的值

var obj6 = {

? a: 3,

? b: 4

}

var obj7 = {...obj, ...obj6}

console.log(obj7)? // {a: 3,b: 4}

// 當(dāng)key值不同時(shí),會(huì)合并構(gòu)造新的對(duì)象

var obj4 = {

? c: 3,

? d: 4

}

var obj5 = {...obj, ...obj4}

console.log(obj5)? // {a: 1,b: 2,c: 3,d: 4}




// 4、字符串轉(zhuǎn)數(shù)組

var dome = "hello";

var arr4 = [...dome];

console.log(arr4)? // ["h", "e", "l", "l", "o"]




// 剩余語(yǔ)法

function text2(a, ...arr5){

? console.log(a)? // 1

? console.log(arr5)? // [2, 3, 4, 5]

}

text2(1,2,3,4,5)



var [a, ...arr6] = [1,2,3,4,5,6]

console.log(a)? // 1

console.log(arr6)? // [2, 3, 4, 5, 6]



var {b, ...obj8} = obj5

console.log(b)? // 2

console.log(obj8)? // {a: 1, c: 3, d: 4}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容