… 拓展运算符
作用:将一个大元素打散成小元素,可作用于数组、字符串、对象等例如:
var array = [1,2,3,4];
console.log(...array);//1 2 3 4
var str = "String";
console.log(...str);//S t r i n g
…有哪些用处呢?
1. 数组、对象的合并和复制
// ... to merge array
let temp1= [1,2,3];
let temp2=[4,5,6];
let arr1 = [...temp1,...temp2]; // arr1 is new array
console.log(arr1) // expected output 1,2,3,4,5,6
// also can be used like this
let temp1.push(...temp2);
// other methods to merge array
let arr2 = temp1.concat(temp2); // arr2 is new array
let arr3 = Object.assign(temp1,temp2)// arr3 === temp1
// can you imagin how to copy an array by ...?
// just like your idea,
let a = [1,2,3];
let b = [...a]
// you can image how to copy or merge object from the example of array
let p0 = {sex: "female"}
let p1 = {name: "lili",age:24};
let p2 = {...p1} // p2 is new objct
console.log(p2)// expected output: {name: "lili",age:24}
let p3 = {...p0,...p1}
console.log(p3) //expected output: {name: "lili",age:24,sex:"female"}
what deserves your special attention is … works as shallow copy.
Let’s see an example
let a = {name: "lily",job:{title: "manager"}};
let b = {...a};
a.job.title = "CEO";
console.log(b) // expect output: {name: "lily",job:{title: "CEO"}};
2. 类数组转为数组
var nodeList = document.querySelectorAll('div'); // nodeList is Pseudo array with other properties except length
let arrayList = [...nodeList];
console.log(arrayList); // [div, div, div ... ] // arrayList a real array
与reset 剩余收集符的关系
reset 剩余收集符如字面意思:就是用来收集剩下的参数,与拓展运算符一样都是用**…** 表示。
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort(); // arguments is an Pseudo array with
}
// 上面可用,reset 剩余收集写作如下
const sortNumbers = (...numbers) => numbers.sort(); // numbers is an real array
// **reset 收集符收集剩下的参数,只能用于最后**
var array = [1,2,3,4,5,6];
var [a,b,...c] = array; // good
var [a,...c,b] = array // bad