es6_数组扩展_扩展运算符
目录
...arr
使用三个点可以将数组转为以逗号分隔的参数序列。
example1.将数组转化为以逗号分隔的参数序列
const ARR1 = [1, 2, 3, 4, 5];
console.log(...ARR1); //1 2 3 4 5
example2.将多个数组进行合并
const ARR1 = [15, 146, 58];
const ARR2 = [13, 15, 12];
const ARR3 = [47, 48, 587];
const ARR4 = [...ARR1, ...ARR2, ...ARR3];
console.log(ARR4); //[15, 146, 58, 13, 15, 12, 47, 48, 587]
example3.将数组子项作为参数传递给函数
const ARR1 = [1, 2, 3, 4, 5, 6];
function add(x, y) {
console.log(x + y);
}
add(...ARR1); //3
example4.与解构配合赋值,但要注意扩展运算符必须在最后一个,否则报错。
let arr = [variable1, ...ARR1] = [1, 2, 3, 4, 5, 6];
console.log(variable1); //1
console.log(ARR1); //[2,3,4,5,6]
let arr2 = [...ARR2, variable2] = [1, 2, 3, 4, 5];
console.log(ARR2);
console.log(variable2);//Uncaught SyntaxError: Rest element must be last element
example5.展开实现了Iterator接口的对象
扩展set
let set1 = new Set();
set1.add(1);
set1.add(2);
set1.add(2);
set1.add(3);
console.log(set1); //可遍历对象[1,2,3],可以使用Array.from转换成数组
console.log(Array.from(set1)); //[1,2,3]
console.log(...set1); //1 2 3
扩展map
let map1 = new Map();
map1.set('k1', 1);
map1.set('k2', 2);
map1.set('k3', 3);
console.log(map1);//可遍历对象
console.log(Array.from(map1)); //[["k1", 1],["k2", 2],["k3", 3]];
console.log(...map1); //["k1", 1] ["k2", 2] ["k3", 3]]
example6.在数组扩展中添加表达式
var x = 1;
var arr1 = [1, 3, 5, 7, 9];
var arr2 = [2, 4, 6, 8, 10];
const ARR = [...(x > 0 ? arr1 : arr2), "奇数"];
console.log(ARR); //[1, 3, 5, 7, 9, "奇数"]
只有函数调用时,整个扩展运算符(包括三个点号)才可以放在圆括号内
example7.复制数组
const A1 = [1, 2];
//第一种复制方法
const A2 = [...A1];
//第二种复制方法
const [...A3] = A1;
console.log(A1); //[1,2]
console.log(A2); //[1,2]
console.log(A3); //[1,2]
两种方法都是浅拷贝
const ARR1 = [{
a: 1
}];
const ARR2 = [{
b: 2
}];
const ARR3 = ARR1.concat(ARR2);
console.log(ARR3);
const ARR4 = [...ARR1, ...ARR2];
console.log(ARR4);
console.log(ARR3[0] === ARR4[0]);
ARR3[0].a = 8;
console.log(ARR4[0]); //{a:8}
修改堆内存中的对象的属性值会直接反映到另一个数组中去
example8.String
console.log([...'hello']); //["h", "e", "l", "l", "o"]
console.log([...'hello'].length); //5
数组拓展使ES5与ES6的之间的区别
替代ES5的apply方法
函数参数传递的简化
function f(x, y, z) {
console.log(x + y + z);
}
var args = [0, 1, 2];
f.apply(null, args); //3 顺带一提因为绑定的上下文为null,所以this指向window对象
f(...args); //3
求出数组中的最大数字
console.log(Math.max.apply(null, [1, 2, 3])); //3
console.log(Math.max(...[1, 2, 3])); //3
console.log(Math.max(1, 2, 3)); //3
将一个数组添加到另一个数组的尾部
var arr1 = [1, 2, 3];
var arr2 = [4, 5, 6];
Array.prototype.push.apply(arr1, arr2);
console.log(arr1); //[1, 2, 3, 4, 5, 6]
arr1 = [1, 2, 3];
arr1.push(...arr2);
console.log(arr1); //[1, 2, 3, 4, 5, 6]
arr1 = [1, 2, 3];
var arr3 = arr1.concat(arr2);
console.log(arr3); //[1, 2, 3, 4, 5, 6]
date对象传入自定义参数
console.log(new(Date.bind.apply(Date, [null, 2015, 1, 1])));
//Sun Feb 01 2015 00:00:00 GMT+0800 (中国标准时间)
console.log(new Date(...[2015, 1, 1]));
//Sun Feb 01 2015 00:00:00 GMT+0800 (中国标准时间)