扩展运算符( spread )是三个点(...)。它比如 rest 参数的逆运算,将一个数组转为用逗号分隔的参数序列。node
console.log(...[1, 2, 3]) // 1 2 3 console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5 [...document.querySelectorAll('div')] // [<div>, <div>, <div>]
array.push(...items)和add(...numbers)这两行,都是函数的调用,它们的都使用了扩展运算符。该运算符将一个数组,变为参数序列。数据库
function push(array, ...items) { array.push(...items) } function add(x, y) { return x + y } var numbers = [4, 38] add(...numbers) // 42
function f(v, w, x, y, z) {} var args = [0, 1] f(-1, ...args, 2, ...[3])
ES5 写法中,push方法的参数不能是数组,因此只好经过apply方法变通使用push方法。
有了扩展运算符,就能够直接将数组传入push方法。数组
// ES5 的写法 function f(x, y, z) {} var args = [0, 1, 2] f.apply(null, args) // ES6 的写法 function f(x, y, z) {} var args = [0, 1, 2] f(...args)
Math.max.apply(null, [14, 3, 77]) // ES5 的写法 Math.max(...[14, 3, 77]) // ES6 的写法 Math.max(14, 3, 77) // 等同于
// ES5 var arr1 = [0, 1, 2] var arr2 = [3, 4, 5] Array.prototype.push.apply(arr1, arr2) // ES6 var arr1 = [0, 1, 2] var arr2 = [3, 4, 5] arr1.push(...arr2)
new (Date.bind.apply(Date, [null, 2015, 1, 1])) // ES5 new Date(...[2015, 1, 1]) // ES6
var dateFields = readDateFields(database) var d = new Date(...dateFields)
扩展运算符还能够将字符串转为真正的数组。数据结构
[...'hello'] // [ "h", "e", "l", "l", "o" ]
上面的写法,有一个重要的好处,那就是可以正确识别 32 位的 Unicode 字符。app
'x\uD83D\uDE80y'.length // 4 [...'x\uD83D\uDE80y'].length // 3
上面代码的第一种写法, JavaScript 会将 32 位 Unicode 字符,识别为 2 个字符,采用扩展运算符就没有这个问题。所以,正确返回字符串长度的函数,能够像下面这样写。函数
function length(str) { return [...str].length } length('x\uD83D\uDE80y') // 3
凡是涉及到操做 32 位 Unicode 字符的函数,都有这个问题。所以,最好都用扩展运算符改写。es5
let str = 'x\uD83D\uDE80y' // str 即 'x🚀y' str.split('').reverse().join('') // 'y\uDE80\uD83Dx' 即 'y��x' [...str].reverse().join('') // 'y\uD83D\uDE80x' 即 'y🚀x'
上面代码中,若是不用扩展运算符,字符串的reverse操做就不正确。prototype
遍历器(Iterator)是一种接口,为各类不一样的数据结构提供统一的访问机制。任何数据结构只要部署Iterator接口,就能够完成遍历操做(即依次处理该数据结构的全部成员)。
任何 Iterator 接口的对象,均可以用扩展运算符转为真正的数组。rest
var nodeList = document.querySelectorAll('div') var array = [...nodeList]
上面代码中,querySelectorAll方法返回的是一个nodeList对象。它不是数组,而是一个相似数组的对象。这时,扩展运算符能够将其转为真正的数组,缘由就在于NodeList对象实现了 Iterator 接口。code
对于那些没有部署 Iterator 接口的相似数组的对象,扩展运算符就没法将其转为真正的数组。
let arrayLike = { '0': 'a', '1': 'b', '2': 'c', length: 3 } let arr = [...arrayLike] // Uncaught TypeError: arrayLike is not iterable Array.from(arrayLike) // ["a", "b", "c"]
上面代码中,arrayLike是一个相似数组的对象,可是没有部署 Iterator 接口,扩展运算符就会报错。这时,能够改成使用Array.from方法将arrayLike转为真正的数组。
扩展运算符内部调用的是数据结构的 Iterator 接口,所以只要具备 Iterator 接口的对象,均可以使用扩展运算符,好比 Map 结构。
let map = new Map([ [1, 'one'], [2, 'two'], [3, 'three'], ]) let arr = [...map.keys()] // [1, 2, 3]
Generator 函数运行后,返回一个遍历器对象,所以也可使用扩展运算符。
var go = function*(){ yield 1 yield 2 yield 3 } [...go()] // [1, 2, 3]
上面代码中,变量go是一个 Generator 函数,执行后返回的是一个遍历器对象,对这个遍历器对象执行扩展运算符,就会将内部遍历获得的值,转为一个数组。
若是对没有iterator接口的对象,使用扩展运算符,将会报错。
var obj = {a: 1, b: 2} let arr = [...obj] // Uncaught TypeError: obj is not iterable