扩展运算符
var foo = function(a, b, c) { console.log(a); console.log(b); console.log(c);}var arr = [1, 2, 3];//传统写法foo(arr[0], arr[1], arr[2]);//使用扩展运算符foo(...arr);//1//2//3
//数组深拷贝var arr2 = arr;var arr3 = [...arr];console.log(arr===arr2); //true, 说明arr和arr2指向同一个数组console.log(arr===arr3); //false, 说明arr3和arr指向不同数组//把一个数组插入另一个数组字面量var arr4 = [...arr, 4, 5, 6];console.log(arr4);//[1, 2, 3, 4, 5, 6]//字符串转数组var str = 'love';var arr5 = [...str];console.log(arr5);//[ 'l', 'o', 'v', 'e' ]
解构赋值
var arr = ['this is a string', 2, 3];//传统方式var a = arr[0], b = arr[1], c = arr[2];//解构赋值,是不是简洁很多?var [a, b, c] = arr;console.log(a);//this is a stringconsole.log(b);//2console.log(c);//3
var arr = [[1, 2, [3, 4]], 5, 6];var [[d, e, [f, g]], h, i] = arr;console.log(d);//1console.log(f);//3console.log(i);//6
rest运算符
//主要用于不定参数,所以ES6开始可以不再使用arguments对象var bar = function(...args) { for (let el of args) { console.log(el); }}bar(1, 2, 3, 4);//1//2//3//4bar = function(a, ...args) { console.log(a); console.log(args);}bar(1, 2, 3, 4);//1//[ 2, 3, 4 ]
rest运算符配合解构使用:
var [a, ...rest] = [1, 2, 3, 4];console.log(a);//1console.log(rest);//[2, 3, 4]