登录
原创

ES6-...扩展运算符、rest参数

发布于 2021-10-11 阅读 280
  • 前端
  • JavaScript
  • ECMAScript 6
原创

ES6中 … 可以表示 扩展运算符 或者 rest参数

扩展运算符- - -实参 + …

…结合实参,则是扩展运算符,将数组或伪数组以 “,” 逗号拆分成一组数据
eg:

function foo(x, y, z) {
    console.log(x, y, z);
}

let arr = [1, 3, 6]
console.log(...arr)
foo(...arr)

还可以应用到数组的合并
push()只能添加数,不能添加数组,合并数组要进行处理

应用:ES5中数组合并

let arr1 = [1, 2, 3]
let arr2 = [3, 6, 8]
Array.prototype.push.apply(arr1, arr2)
console.log(arr1)

打印结果:

image.png

应用:ES6中数组合并

let arr1 = [1, 2, 3]
let arr2 = [3, 6, 8]

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

打印结果和上面一样:

image.png

rest参数- - -形参 + …

function foo(...args) {
    let sum = 0;
    args.forEach(function(item) {
        sum += item
    })
    return sum
}

console.log(foo(1,5))
console.log(foo(2, 8, 10))

打印结果:

image.png

如果前面有确定要传的参数,后面参数个数不确定,可以这样
eg:

function foo(a, ...args) {
    console.log(a);
    console.log(args);
}
foo(666, 9, 10, 888)
foo(222, 6, 6, 6, 10)

打印结果:

image.png

还可以运用到解构赋值:

let [x, ...y] = [2, 999, 1010, 666]
console.log(x)
console.log(y)

打印结果:

image.png

评论区

零00
7粉丝

时光荏苒,我自清欢

0

0

0

举报