繁体   English   中英

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

[英]Is It Possible To Set Default Parameter Value On A Rest Parameter

ES6 引入了一堆方便的“语法糖”。 其中包括 JavaScript 函数的默认参数能力,以及其余参数 我发现每当尝试在 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(', ')}`;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM