JavaScript是ECMAScript的实现和扩展,ES6标准的制定也为JavaScript加入了许多新特性。本文主要记录展开运算符。
展开运算符(spread operator)允许一个表达式在某处展开。展开运算符在多个参数(用于函数调用)或多个元素(用于数组字面量)或者多个变量(用于解构赋值)的地方可以使用。
展开运算符不能用在对象当中,因为目前展开运算符只能在可遍历对象(iterables)可用。iterables的实现是依靠[Symbol.iterator]函数,而目前只有Array,Set,String内置[Symbol.iterator]方法,而Object尚未内置该方法,因此无法使用展开运算符。不过ES7草案当中已经加入了对象展开运算符特性。
函数调用中使用展开运算符
在以前我们会使用apply方法来将一个数组展开成多个参数:1
2
3function test(a, b, c) { }
var args = [0, 1, 2];
test.apply(null, args);
如上,我们把args数组当作实参传递给了a,b,c,这边正是利用了Function.prototype.apply的特性。
不过有了ES6,我们就可以更加简洁地来传递数组参数:1
2
3function test(a,b,c) { }
var args = [0,1,2];
test(...args);
数组字面量中使用展开运算符
1 | var arr1=['a','b','c']; |
用于解构赋值
let [pivot,...rest] = arr
.只能用在数组最后。
剩余对象必须用在最后,…spread可以用在中间。
类数组对象变成数组
展开运算符可以将一个类数组对象变成一个真正的数组对象:1
2var list=document.getElementsByTagName('div');
var arr=[...list];
ES7草案中的对象展开运算符
spread可以对对象进行操作,提取对象中的元素。1
2
3
4let {x,y,...z}={x:1,y:2,a:3,b:4};
x; //1
y; //2
z; //{a:3,b:4}