ES6學(xué)習(xí)第七節(jié):Array擴展

  • 擴展運算符

擴展運算符(spread)是三個點(...)。它好比 rest 參數(shù)的逆運算,將一個數(shù)組轉(zhuǎn)為用逗號分隔的參數(shù)序列。

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

function add(x, y) {
  return x + y
}
const numbers = [4, 38]
// 擴展運算符,將傳入的數(shù)組變?yōu)閰?shù)序列
console.log(add(...numbers)) // 42
console.log(add.apply(null, numbers)) // 42
  • 替代apply方法
function add(x, y) {
  return x + y
}
const numbers = [4, 38]
// ES6寫法
console.log(add(...numbers)) // 42
// ES5寫法
console.log(add.apply(null, numbers)) // 42

console.log(Math.max.apply(null, [14, 2, 77])) // 77
console.log(Math.max(...[14, 2, 77])) // 77
console.log(Math.max(14, 2, 77)) // 77

擴展運算符的應(yīng)用

  • 復(fù)制數(shù)組
var a1 = [1, 2]
var a2 = [...a1]
a1[0] = 2
console.log(a1); // [2,2]
console.log(a2) // [1,2]
  • 合并數(shù)組
const arr1 = ['a', 'b']
const arr2 = ['c']
const arr3 = ['d', 'e']
console.log(arr1.concat(arr2, arr3)) // [ 'a', 'b', 'c', 'd', 'e' ]
console.log([...arr1, ...arr2, ...arr3]) // [ 'a', 'b', 'c', 'd', 'e' ]
  • 與解構(gòu)賦值結(jié)合
const [first, ...rest] = [1, 2, 3, 4, 5]
console.log(first, rest) // 1 [ 2, 3, 4, 5 ]
  • 字符串
console.log([...'Hello']) // [ 'H', 'e', 'l', 'l', 'o' ]
  • Map、Set和Generator函數(shù)

具有 Iterator 接口的對象,都可以使用擴展運算符

let map = new Map([[1, 'one'], [2, 'two'], [3, 'three']])
console.log([...map.keys()])
const set = new Set([1, 2, 3, 4])
console.log(...set)

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

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

  • 函數(shù)參數(shù)的默認值 基本用法 在ES6之前,不能直接為函數(shù)的參數(shù)指定默認值,只能采用變通的方法。 上面代碼檢查函數(shù)l...
    呼呼哥閱讀 3,703評論 0 1
  • 函數(shù)參數(shù)的默認值 基本用法 在ES6之前,不能直接為函數(shù)的參數(shù)指定默認值,只能采用變通的方法。 上面代碼檢查函數(shù)l...
    陳老板_閱讀 512評論 0 1
  • 三,字符串?dāng)U展 3.1 Unicode表示法 ES6 做出了改進,只要將碼點放入大括號,就能正確解讀該字符。有了這...
    eastbaby閱讀 1,667評論 0 8
  • 1.函數(shù)參數(shù)的默認值 (1).基本用法 在ES6之前,不能直接為函數(shù)的參數(shù)指定默認值,只能采用變通的方法。
    趙然228閱讀 829評論 0 0
  • 不眠識幾更,披衣望申星。 竹疏著露寒,萬籟寂無聲。 注:申星,是鄉(xiāng)下人說法,是三顆星排成一條線,時辰不同它的位置不...
    陽春閱讀 286評論 0 2

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