ES6-数组+扩展运算符

1、使用扩展运算符,将数组进行展开

console.log(...[1,2,3,4,5]) // 1 2 3 4 5

let arr = [
    ...(x > 0 ? [1,2,3]: [4,5,6]),
    7,8,9
]

[...[]] // []
[...[], 1] // [1]

2、扩展运算符可以用于函数传参,rest参数

function aaa(x, ...rest){
    
    
    console.log(rest); // [2,3,5,6]
}
aaa(1,...[2,3], 5, 6)

3、使用扩展运算符,替代apply方法

// 运用场景1:函数传参
function x(x, y, z) {
    
    }
let arr = [1,2,3]
x.apply(null, arr) // 可以使用 x(...arr) 直接代替
x(...arr)


// 运用场景2:Math.max()
Math.max.apply(null, [1,2,3,4]) // 4
Math.max(...[1,2,3,4]) // 4
Math.max(1,2,3,4) // 4


// 运用场景3:数组 push
let rr1 = [1,2,3]
let rr2 = [4,5,6]
Array.prototype.push.apply(rr1, rr2) 
console.log(rr1) //[1, 2, 3, 4, 5, 6]
console.log(rr1.push(...rr2)) // [1, 2, 3, 4, 5, 6] -> 作用相当于Array.prototype.push.apply(rr1, rr2) 

4、使用扩展运算符,复制数组

let a = [1,2,3]
let b = [...a] // [1,2,3]
let [...c] = a // [1,2,3]
b[0] = 1111
c[0] = 222
console.log(a) // [1, 2, 3]
console.log(b) // [1111, 2, 3]
console.log(c) // [222, 2, 3]

5、使用扩展运算符,合并数组

let a1 = [1,2]
let a2 = [3,4]
let a3 = [5,6]
let res1 = a1.concat(a2).concat(a3) // 浅拷贝
let res2 = [...a1, ...a2, ...a3] // 浅拷贝

6、与解构赋值结合使用

let a = [1,2,3,4]
let [x, ...rest] = a // x->1 rest->[2,3,4]

7、与字符串结合使用

[...'hello'] //  ['h', 'e', 'l', 'l', 'o']

8、扩展运算符与 Map、Set及 Generate函数结合使用

let map = new Map([['222', 222],[true, 1], [false, 0], ['aaa', 'a']])
let keys = [...map.keys()] // ['222', true, false, 'aaa']

let arr = [1,2,3,4]
let set = new Set([...arr])

let go = function*() {
    
    
  yield 1;
  yield 2;
  yield 3;
}
[...go()] // [1,2,3]

就记录到这,祝大家开心!
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_37600506/article/details/123280975
今日推荐