es6之擴充套件運算子

2021-09-25 13:23:03 字數 2260 閱讀 3948

在es6以前,如果我們要把兩個陣列拼接到一起,通常是使用陣列的concat方法,比如

const a = ['jelly', 'bob', 'helen'];

const b = ['james', 'adrew', 'john'];

const c = a.concat(b);

console.log(c);

// ['jelly', 'bob', 'helen', 'james', 'adrew', 'john']

上面這種方法,如果想要在中間多加乙個名字,使用的方法通常是

let members = ;

members = merbers.concat(a);

members.push('mary');

members = merbers.concat(b);

console.log(members);

// ['jelly', 'bob', 'helen', 'mary', 'james', 'adrew', 'john']

這樣寫,是不是感覺比較麻煩呢

於是,es6新出的擴充套件運算子就可以很好的拯救這個問題,什麼是擴充套件運算子呢,下面給乙個小**了解一下,字串是可遍歷物件,使用擴充套件運算子可以擴充套件其中的每乙個字元

["visit"]

[...'visit']

// ["v", "i", "s", "i", "t"]

上面可以看到,字串的每乙個元素被擴充套件到新的陣列當中了,

陣列也是可遍歷物件,因此,之前的**可以簡寫為

let members = [...a, ...b];

console.log(members);

// ['jelly', 'bob', 'helen', 'james', 'adrew', 'john']

let members2 = [...a, 'mary', ...b];

console.log(members2);

// ['jelly', 'bob', 'helen', 'mary', 'james', 'adrew', 'john']

擴充套件運算子還可以用於複製陣列

以前,我們通常這樣寫

const members =  ['jelly', 'bob', 'helen', 'james', 'adrew', 'john'];

const memberscopy = members;

console.log(memberscopy);

// ['jelly', 'bob', 'helen', 'james', 'adrew', 'john'];

但是,如果你改變了新陣列成員裡面的值,原陣列的值也會被改變,比如下面這種情況

memberscopy[0] = 'thomas'

console.log(memberscopy);

// ['thomas', 'bob', 'helen', 'james', 'adrew', 'john'];

console.log(members);

// ['thomas', 'bob', 'helen', 'james', 'adrew', 'john'];

因為這種**複製的不是陣列,而是陣列的索引

解決方法

第一種,以前的寫法

const members =  ['jelly', 'bob', 'helen', 'james', 'adrew', 'john'];

const memberscopy = .concat(members);

第二種,es6擴充套件運算子

const members =  ['jelly', 'bob', 'helen', 'james', 'adrew', 'john'];

const memberscopy = [...members];

擴充套件運算子在函式中的運用

const newfruit = ['orange', 'mongo'];

fruit.push(newfruit);

console.log(fruit);

正確的做法

console.log(fruit);

fruit.push(...newfruit);

console.log(fruit);

ES6之擴充套件運算子 「 」

es6中的擴充套件運算子就是三個點 可以用來將乙個陣列分割為由陣列內容組成的引數序列。1 可以將陣列轉換為分隔開的字串 2 擴充套件運算子可以用於函式呼叫 1 將引數集成為陣列 function show a show 1,2,3,4,5 1,2,3,4,5 2 將陣列展開為相對應的引數 funct...

ES6 擴充套件運算子

擴充套件運算子用3個點表示,功能是把陣列或者類陣列物件展開成一系列用逗號隔開的值 1,陣列 let arr red green blue console.log arr red,green,blue拷貝陣列 和object.assign一樣都是淺拷貝 let arr red green blue l...

ES6擴充套件運算子

首先,我們要讀仔細下面這句話,就很容易知道擴充套件運算子的使用了,可以在心裡反覆讀三遍 接下來,我們看下究竟怎麼個情況 宣告乙個方法 var foo function a,b,c console.log a console.log b console.log c 宣告乙個陣列 var arr 1,2...