… 拓展运算符
作用:将一个大元素打散成小元素,可作用于数组、字符串、对象等例如:
var array = [1,2,3,4];
console.log(...array);
var str = "String";
console.log(...str);
…有哪些用处呢?
1. 数组、对象的合并和复制
let temp1= [1,2,3];
let temp2=[4,5,6];
let arr1 = [...temp1,...temp2];
console.log(arr1)
let temp1.push(...temp2);
let arr2 = temp1.concat(temp2);
let arr3 = Object.assign(temp1,temp2)
let a = [1,2,3];
let b = [...a]
let p0 = {sex: "female"}
let p1 = {name: "lili",age:24};
let p2 = {...p1}
console.log(p2)
let p3 = {...p0,...p1}
console.log(p3)
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)
2. 类数组转为数组
var nodeList = document.querySelectorAll('div');
let arrayList = [...nodeList];
console.log(arrayList);
与reset 剩余收集符的关系
reset 剩余收集符如字面意思:就是用来收集剩下的参数,与拓展运算符一样都是用**…** 表示。
function sortNumbers() {
return Array.prototype.slice.call(arguments).sort();
}
const sortNumbers = (...numbers) => numbers.sort();
var array = [1,2,3,4,5,6];
var [a,b,...c] = array;
var [a,...c,b] = array
|