编程语言
首页 > 编程语言> > javascript – 是否可以在其余参数上设置默认参数值

javascript – 是否可以在其余参数上设置默认参数值

作者:互联网

ES6引入了一系列方便的“语法糖”.其中包括JavaScript函数的default parameter功能,以及rest parameters.我发现我的控制台(或devTools)在尝试在rest参数上设置默认参数值时会抱怨(即抛出错误).我发现在其他地方很少引用这个特定的问题,我想知道是否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(', ')}`

标签:spread-syntax,javascript,ecmascript-6,default-value
来源: https://codeday.me/bug/20190929/1831217.html