ES6学习第七节:Array扩展

  • 扩展运算符

扩展运算符(spread)是三个点(...)。它好比 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。

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

function add(x, y) {
  return x + y
}
const numbers = [4, 38]
// 扩展运算符,将传入的数组变为参数序列
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

扩展运算符的应用

  • 复制数组
var a1 = [1, 2]
var a2 = [...a1]
a1[0] = 2
console.log(a1); // [2,2]
console.log(a2) // [1,2]
  • 合并数组
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' ]
  • 与解构赋值结合
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函数

具有 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())
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 函数参数的默认值 基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。 上面代码检查函数l...
    呼呼哥阅读 8,986评论 0 1
  • 函数参数的默认值 基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。 上面代码检查函数l...
    陈老板_阅读 3,328评论 0 1
  • 三,字符串扩展 3.1 Unicode表示法 ES6 做出了改进,只要将码点放入大括号,就能正确解读该字符。有了这...
    eastbaby阅读 5,515评论 0 8
  • 1.函数参数的默认值 (1).基本用法 在ES6之前,不能直接为函数的参数指定默认值,只能采用变通的方法。
    赵然228阅读 4,127评论 0 0
  • 不眠识几更,披衣望申星。 竹疏着露寒,万籟寂无声。 注:申星,是乡下人说法,是三颗星排成一条线,时辰不同它的位置不...
    陽春阅读 1,810评论 0 2

友情链接更多精彩内容