扩展运算符
1.数组的合并
方法 1
let a = [1,2,3];
let b = [2, 3, 4];
let c = [...a, ...b];
console.log(c)
方法2
let a = [1,2, 3]
let b = [2, 3, 4]
a.push(...b)
console.log(a)
2.简化传值
const arr = [1, 2, 3]
function f(a, b, c) {
console.log(a,b,c)
}
f(...arr)
f.call(null, ...arr)
function f2(...args){
console.log(args)
}
f2(1,2,3) // [1,2,3]
转换伪数组
const arr = [1, 2, 3];
function f(a, b, c) {
console.log(...arguments); // 1 2 3
let bbbb = [...arguments];
console.log(bbbb[0]) // 1
}
f.call(null, ...arr)
解构赋值
let[a, ...b] = [1,2,3,4];
console.log(a) // 1
console.log(b) // [2,3,4]
字符串转为数组,识别 32 位的 Unicode 字符
let a = [...'yang']
console.log(a) //["y", "a", "n", "g"]
let b = [...'x\uD83D\uDE80y'];
console.log(b) //["x", "🚀", "y"]
具有 Iterator 接口的对象,转换成数组
var nodeList = document.querySelectorAll('li');
console.log([...nodeList]) // 转成数组
var mapList = new Map([[3,33],[4,44],[5,55]]);
console.log([...mapList .keys()]); // [3,4,5]
且拷贝
var a = {
a:1,
b:2
}
var b = {...a};
b.a = 2;
console.log(a.a) // 1
console.log(b.a) // 2
var a = [ 1, 2, 3 ];
var b = [ 3, 4, ...a ];
console.log(b) // [3, 4, 1, 2, 3]