咏竹莉
where there is a will,there is a way

ES6 拓展运算符 

1.数组(扩展运算符)

解构赋值
扩展运算符(spread)就是我们知道的三个点(...),它就好像rest参数的逆运算,将一个数组转为用逗号分隔的参数序列。

console.log(...[1,2,3]);
//1 2 3
console.log(1,...[2,3,4],5)
//1 2 3 4 5
console.log([1,...[2,3,4],5])
//[1, 2, 3, 4, 5]
[...document.querySelectorAll('div')]
// [<div>, <div>, <div>]

 

复制数组

let arr = [1, 2],
    arr1 = [...arr];
console.log(arr1); // [1, 2]
// 数组含空位
let arr2 = [1, , 3],
    arr3 = [...arr2];
console.log(arr3); [1, undefined, 3]

 

合并数组

console.log([...[1, 2],...[3, 4]]); // [1, 2, 3, 4]
// 本质也是:**将一个数组转为用逗号分隔的参数序列,然后置于数组中**

 

2. 对象

拓展运算符(...) 用于取出 参数对象 所有可遍历属性 然后拷贝到当前对象

基本用法

let person = {name: "小猪", age: 19}
let someone = {...person}
console.log(someone);  // {name: "小猪", age:19 }

 

合并对象

let name = { name: "小猪" }
let age = {age: 19}
let person = {...name,...age}
console.log(person)  // {name: "小猪", age: 19}

 

注意:自定义的属性在拓展运算符后面,则拓展运算符对象内部同名的属性将被覆盖掉。同理。自定义的属性在拓展运算符前面,则变成设置新对象默认属性值

 

3. 函数

不定参数用来表示不确定参数个数,形如, ...变量名 ,由 ...加上一个具名参数标识符组成。 具名参数只能放在参数组的最后,并且有且只有一个不定

基本用法

function f(...values) {
  console.log(values.length);
}

f(1,2) ;   // 2
f(1,2,3,4);   // 4
  // 函数调用,拓展运算符(...) ,将一个数组,变为参数序列

function addNumbers(x,y,z) { return x + y + z } console.log(addNumbers(...[1,2,3,4])) // 6

 

拓展运算符与政策的函数参数可以结合使用

function f(x,y,z,v,w){
    console.log(x,y,z,v,w)
}
var args = [0,1,5];
var args1 = [0,1];
f(-1,...args,2,...[3]);//-1, 0, 1, 5, 2
f(-1,...args1,2,...[3]);//-1, 0, 1, 2, 3

 

 

posted on 2021-03-05 11:02  咏竹莉  阅读(104)  评论(0)    收藏  举报