在ES6中,引入了两个非常强大的方法:扩展运算符以及Array.from.
扩展运算符
扩展运算符是一个特殊的数组方法,写法是[…argment],argment可以是数组,也可以是字符串,甚至也可以是一个遍历器接口对象,类似Generator函数的返回值。
扩展运算符的作用
合并数组
[...[1,2,3], ...[4,5,6]] //[1,2,3,4,5,6]
将字符串拆分为转为数组
[...'cccccc'] //["c", "c", "c", "c", "c", "c"]
//还可以转化Unicode编码格式为字符串并拆分为数组
[...'x\uD83D\uDE80y'] // ["x", "?", "y"]
将遍历器接口对象转化为数组
Number.prototype[Symbol.iterator] = function*() {
let i = 0;
let num = this.valueOf();
while (i < num) {
yield i++;
}
}
console.log([...5]) // [0, 1, 2, 3, 4]
Array.from方法
Array.from方法用于将两类对象转为真正的数组:类似数组的对象(array-like object)和可遍历(iterable)的对象(包括 ES6 新增的数据结构 Set 和 Map)。
var obj = {
'0': 1,
'1': 2,
'2': 3,
length: 3
}
Array.from(obj) //[1,2,3]
上面代码中,length这一行必不可少,如果缺失,则会输出空数组。
Array.from方法还可以将字符串拆分为数组
Array.from('hello') //["h", "e", "l", "l", "o"]