JavaScript 中... 三个点的使用
都知道在java 中,方法的最后一个形参有可能会出现String… strings的形式,表示此方法可以传任意多个字符串,最终所有字符串组合成String的数组,那么JavaScript中…加名字的使用方法又是如何。
1. 将字符串转字符数组
let a="1asfasfasd1张飒飒的" let b=[...a]; console.log(b);
效果
2. 从集合中拿值时拿取所有剩下的部分
let a={ me: "Bruce", T: "Elon", A: "Tim", MS: "Bill", }; let {me, A,...others}=a;//此处表示从a集合拿出me,拿出A,剩下的是others console.log(A); console.log(others);
效果
3. 解包可迭代对象
3.1. 拼接数组
let l1 = [1,2] let l2 = [1,2] let l3 = [3,4] l1.push(...l3) l2.push(l3)
效果
3.2. 复制数组(防止数组直接赋值地址)
let l1 = [1,2]; let l2 = l1; l1[0]=5; console.log(l2); //l2结果也改变 let l3 = [1,2]; let l4 = [...l3]; l3[0]=5; console.log(l4); //l4结果不改变
效果
3.3. 合并对象
let obj1 = {a:1,b:2} let obj2 = {c:3,d:4} let allObj = {...obj1,...obj2} console.log(allObj)
效果
3.4. 使用数学函数更简单
let a = [1,2,2077,1] Math.max(a) Math.max(...a)
效果
4. 为 JavaScript 函数定义 Rest 参数
同java中若干参数…用法
ceshi(...input){ let ret = 0; for(const i of input){ ret+=i; } return ret; }
console.log("-------------------------"); console.log(this.ceshi(1,2,3,4)); console.log("-------------------------");
效果