是否可以在休息参数上设置默认参数值

Is It Possible To Set Default Parameter Value On A Rest Parameter

ES6 引入了一大堆方便的"syntactic sugar"。其中就有default parameter capabilities of JavaScript functions, as well as rest parameters。我发现每当尝试在 rest 参数上设置默认参数值时,我的控制台(或 devTools)都会抱怨(,抛出错误)。令人惊讶的是,我在其他地方发现很少提到这个特定问题,我想知道 1.) 是否有可能这样做以及 2.) 为什么不是(假设这是不可能的)。

例如,我设计了一个微不足道的(但希望仍然有用的)示例。在函数的第一次迭代中,我构建了函数,使其可以工作(也就是说,没有给 rest 参数一个默认值)。

const describePerson = (name, ...traits) => `Hi, ${name}! You are ${traits.join(', ')}`;

describePerson('John Doe', 'the prototypical placeholder person');
// => "Hi, John Doe! You are the prototypical placeholder person"

但是,现在使用默认值:

const describePerson = (name, ...traits = ['a nondescript individual']) => `Hi, ${name}! You are ${traits.join(', ')}`;

describePerson('John Doe');
// => Uncaught SyntaxError: Unexpected token =

非常感谢任何帮助。

不,其余参数不能有默认初始化程序。语法不允许这样做,因为初始化程序永远不会是 运行 - 参数 总是 被分配一个数组值(但可能是一个空值)。

你想做的事情可以通过

实现
function describePerson(name, ...traits) {
     if (traits.length == 0) traits[0] = 'a nondescript individual';
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}

function describePerson(name, firstTrait = 'a nondescript individual', ...traits) {
     traits.unshift(firstTrait);
     return `Hi, ${name}! You are ${traits.join(', ')}`;
}

// the same thing with spread syntax:
const describePerson = (name, firstTrait = 'a nondescript individual', ...otherTraits) =>
    `Hi, ${name}! You are ${[firstTrait, ...otherTraits].join(', ')}`

刚来添加一个更干净的默认系统:

const describePerson = (name, ...traits) => {
  traits = Object.assign(['x', 'y'], traits);

  return `Hi, ${name}, you are ${traits.join(', ')}`;
}

describePerson('z'); // you are z, y
describePerson('a', 'b', 'c'); // you are a, b, c
describePerson(); // you are x, y

这是可行的,因为数组是索引为键的对象,Object.assign用第二个对象的值覆盖第二个对象中存在的第一个对象的键。

如果第二个没有索引 1,那么它不会被覆盖,但如果它有索引 0,第一个数组的索引 0 将被第二个覆盖,这是您在默认时预期的行为

请注意,展开数组与展开对象的操作不同,这就是 [....['x', 'y'], ...traits] 不会覆盖索引的原因

有解决办法:

const describePerson = (name, ...[
  first = 'a nondescript individual',
  ...traits
]) => `Hi, ${name}! You are ${[first, ...traits].join(', ')}`;