Js拓展运算符(...)

本文深入探讨了JavaScript中的拓展运算符(...)的用途,包括数组和对象的合并与复制、类数组转为数组。拓展运算符可以实现浅拷贝,并在函数参数中收集剩余值。示例展示了如何利用它进行高效操作,同时提醒注意其浅拷贝特性可能导致的意外修改。
摘要由CSDN通过智能技术生成

… 拓展运算符

作用:将一个大元素打散成小元素,可作用于数组、字符串、对象等例如:

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值