美文网首页JavaScript
ES6学习第七节:Array扩展

ES6学习第七节:Array扩展

作者: ChangLau | 来源:发表于2019-02-15 17:48 被阅读0次
  • 扩展运算符

扩展运算符(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())

相关文章

  • ES6新增特性(二)

    ES6 的内置对象扩展 Array 的扩展方法 一、Array 的扩展方法 1. 扩展运算符(展开语法) 扩展运算...

  • ES6学习第七节:Array扩展

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

  • 数组去重

    传统方法 ES6 扩展 传统方法 最后再写到 Array.prototype 原型中

  • JavaScript ES6 - 数组扩展

    本章节的主要内容是: ES6 数组扩展 如图所示: 1. ES6 Array.from() 2. ES6 Arra...

  • ES6快速学习(四)扩展运算符

    扩展运算符 => ... 快速复制一个数组 ES6以前 Array.from() 详细使用请点击Array.f...

  • ES6&数组扩展

    ES6数组扩展 1.Array.from() 定义:Array.from()用于将两类对象转换成真正的数组:类数组...

  • ES6 数组新用法(一)

    《深入理解ES6》阅读随笔 在 ES6 中,对数组功能进行了扩展。可以使用新增的 Array.of() 和 Arr...

  • 【JavaScript高程总结】ES6 数组拓展

    ES6 数组拓展 ES6为Array新增的扩展 ...**(拓展运算符)---三个点将一个数组转为用逗号分隔的参数...

  • 数组去重的几个方案

    数组去重,直接扩展原型方法unique 方法1: 利用知识点:Set()、Array.from() ES6新增的数...

  • ES6语法——数组Array扩展

    一、 扩展运算符 扩展运算符(spread)是三个点(...)。它好比 rest 参数(将多余的参数转换成数组)的...

网友评论

    本文标题:ES6学习第七节:Array扩展

    本文链接:https://www.haomeiwen.com/subject/tilmeqtx.html