ES6--函数的扩展--rest参数(...)

ES6引入rest参数,形式为...变量名,用于获取函数多余参数。

语法:

function foo(a, b, ...args) {
    // ...
}

rest参数只能作为最后一个参数,否则会报错

function foo(a, b, ...args, c) {
    console.log(args)
}
foo(1, 2, 3, 5, 4, 6)
// Syntax error 语法错误

使用举例

function sum(...args) {
    return args.reduce((pre, cur) => {
        return pre + cur
    })
}

console.log(sum(1, 2, 3))   //6

与arguments的区别

  • 剩余参数只包含没有对应形参的实参,而arguments对象包含所有实参
  • 剩余参数是数组,arguments是类数组
  • arguments还有一些附加的属性,如callee
// arguments变量的写法
function sortNumbers() {
    //类数组不能直接使用数组方法
    return Array.prototype.slice.call(arguments).sort();
}

// rest参数的写法
const sortNumbers = (...numbers) => numbers.sort();

扩展知识点:类数组转数组

解构结合

function f(...[a, b, c]) {
    return a + b + c;
}

f(1)          // NaN (b and c are undefined)
//rest =[1],可理解为[a,b,c]=[1],得到a=1, b=undefined, c=undefined
f(1, 2, 3)    // 6
//rest =[1, 2, 3],可理解为[a,b,c]=[1, 2, 3],得到a=1, b=2, c=3
f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
//rest =[1, 2, 3, 4],可理解为[a,b,c]=[1, 2, 3, 4],得到a=1, b=2, c=3,后面的参数会忽略

扩展知识点:解构赋值

面试题

function foo(...args) {
    console.log(typeof args)
}
foo(1)  //object

args是数组,typeof检测数组结果为object

原文地址:https://www.cnblogs.com/lianglanlan/p/14410906.html