你可以通過展開操作符(Spread operator)...擴展一個數組對象和字符串。展開運算符(spread)是三個點(…),可以將可迭代對象轉為用逗號分隔的參數序列。如同rest參數的逆運算。
用于數組
以數組為例,首先創建一個數組,
const a = [1, 2, 3], b = [4,5,6];
你可以輕松賦值一個數組:
const c = [...a] // [1,2,3]
你還可以輕松拼接兩個數組:
const d = [...a,...b] // [1,2,3,4,5,6]
也可以如下拼接
const d = [...a,4, 5, 6] // [1,2,3,4,5,6]
如果要把一個數組b的元素全部插入到數組a的后面(不生成新數組),可以這樣操作:
const a = [1,2,3];a.push(...b);
如果要把一個數組b的元素全部插入到數組a的前面(不生成新數組),可以這樣操作:
const a = [1,2,3];a. unshift(...b);
類數組對象變成數組
可以通過展開運算符把類數組對象變成真正的數組:
var list=document.getElementsByTagName('a');var arr=[..list];
用于對象
展開操作符同樣可以用于對象??梢酝ㄟ^以下方式clone一個對象:
const newObj = { ...oldObj }
注意: 如果屬性值是一個對象,那么只會生成一個指向該對象的引用,而不會深度拷貝。也就是說,展開運算符不會遞歸地深度拷貝所有屬性。并且,只有可枚舉屬性會被拷貝,原型鏈不會被拷貝。
還可以用于merge兩個對象。
const obj1 = { a: 111, b: 222 };const obj2 = { c: 333, d: 444 };const merged = { ...obj1, ...obj2 };console.log(merged); // -> { a: 111, b: 222, c: 333, d: 444 }
當然也可以適用于以下的情況:
const others = {third: 3, fourth: 4, fifth: 5}const items = { first:1, second:1, ...others }items //{ first: 1, second: 2, third: 3, fourth: 4, fifth: 5 }
如果merge的多個對象有相同屬性,則后面的對象的會覆蓋前面對象的屬性,比如
const obj1 = { a: 111, b: 222 };const obj2 = { b: 333, d: 444 };const merged = { ...obj1, ...obj2 };console.log(merged); // -> { a: 111, b: 333, d: 444 }const obj1 = {a:111,b:222}const merged = {a:222,...obj1}; console.log(merged); // -> { a: 111, b: 333 }const obj1 = {a:111,b:222}const merged = {...obj1,a:222}; console.log(merged); // -> { a: 222, b: 333 }
用于字符串
通過展開操作符,可以把一個字符串分解成一個字符數組,相當于
const hey = 'hey'const arrayized = [...hey] // ['h', 'e', 'y']
以上代碼相當于:
const hey = 'hey'const arrayized = hey.split('') // ['h', 'e', 'y']
用于函數傳參
通過展開操作符,可以通過數組給函數傳參:
const f = (foo, bar) => {}const a = [1, 2]f(...a)const numbers = [1, 2, 3, 4, 5]const sum = (a, b, c, d, e) => a + b + c + d + econst sum = sum(...numbers)
用于具有 Iterator 接口的對象
具有 Iterator 接口的對象Map 和 Set 結構,Generator 函數,可以使用展開操作符,比如:
var s = new Set();s.add(1);s.add(2);var arr = [...s]// [1,2]function * gen() { yield 1; yield 2; yield 3;}var arr = [...gen()] // 1,2,3
如果是map,會把每個key 和 value 轉成一個數組:
var m = new Map();m.set(1,1)m.set(2,2)var arr = [...m] // [[1,1],[2,2]]
注意以下代碼會報錯,因為obj不是一個Iterator對象:
var obj = {'key1': 'value1'};var array = [...obj]; // TypeError: obj is not iterable
以上就是全部相關知識點,感謝大家的閱讀和對VeVb武林網的支持。
新聞熱點
疑難解答