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]

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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值