学习笔记 JavaScript ES6 扩展运算符与rest参数(也称剩余参数)

学习内容:

  • ...

  • 扩展运算符:把数组或类数组展开成用逗号分隔的值
  • rest参数:把逗号隔开的值组成一个数组

扩展运算符

...如果放在等号的左边,或在形参上就是rest参数,
如果...在等号右边,或在实参上就是扩展运算符

使用场景1:

// 前面学习过解构赋值,但下面这种形式不是解构
// 解构要求两边形式完全一样,如果要改成解构赋值
// 需要把函数test的参数也改成数组[a,b,c],
// 但这就和原始需求不一致了

function test(a, b, c) {
    console.log(a,b,c)
}

let arr = [1,2,3]
test(arr)

------------------------------
[1, 2, 3] undefined undefined

使用“...”扩展运算符把数组展开成用逗号分隔的值

注意:

定义了遍历器接口的对象才能使用扩展运算符转化为数组。

类数组没有部署 Iterator 接口所以扩展运算符会报错。

// 扩展运算符的应用

function test(a, b, c) {
    console.log(a,b,c)
}

let arr = [1,2,3]
test(...arr) // 注意这里...

--------------------------------
1 2 3

使用场景2:

ES5数组的合并

let arr1 = [1,2,3]
let arr2 = [4,5,6]

// ES5当中把两个数组合并为一个,除了写循环再push,
// 注意push只能push值,不能push数组
// 也可以使用下面的代码合并
Array.prototype.push.apply(arr1,arr2)
console.log(arr1)

----------------------
(6) [1, 2, 3, 4, 5, 6]

ES6数组的合并

let arr1 = [1,2,3]
let arr2 = [4,5,6]

arr1.push(...arr2)
console.log(arr1)

-----------------------------
(6) [1, 2, 3, 4, 5, 6]

使用场景3:

把字符串转为数组

let str = 'imooc'
var arr = [...str]
console.log(arr)

------------------------------
(5) ['i', 'm', 'o', 'o', 'c']

使用场景4:

对不确定参数的求和

ES5写法:

function test(x, y, z) {
    // console.log(arguments)
    let sum = 0
    Array.prototype.forEach.call(arguments, function (item) {
        sum += item
    })

    return sum
}

console.log(test(1, 2))
console.log(test(1, 2, 3))

-------
3
6
function test(x, y, z) {
    // console.log(arguments)
    let sum = 0
    // Array.prototype.forEach.call(arguments, function (item) {
    //     sum += item
    // })

    Array.from(arguments).forEach(function (item) { // ES6把类数组转为数组的写法
        sum += item
    })

    return sum
}

console.log(test(1, 2))
console.log(test(1, 2, 3))

 ES6写法:

使用...rest参数

function test(...args) { // 注意这里就是rest参数
    
    console.log(args)
    let  sum = 0
    args.forEach(function(item) {
        sum += item
    })

    return sum
}

console.log(test(1, 2))
console.log(test(1, 2, 3))

----------------------------------
(2) [1, 2]
3
(3) [1, 2, 3]
6

下面这个例子,x参数一定会传,其它的参数不会传,也就是说剩下的参数...args全管了,也就是理解为剩余参数

function test(x, ...args) {
    console.log(x)
    console.log(args)
}

test(1, 2, 3)
test(1, 2, 3, 4)

--------------------------
1
(2) [2, 3]
1
(3) [2, 3, 4]

使用场景5:

与解构联合使用

let [x, ...y] = [1, 2, 3]
console.log(x)
console.log(y)

-----------------
1
(2) [2, 3]

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值