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

后端 未结 2 589
Happy的楠姐
Happy的楠姐 2020-12-11 01:43

ES6 introduces a bevy of convenient \"syntactic sugar\". Among them are the default parameter capabilities of JavaScript functions, as well as rest parameters. I\'m finding

2条回答
  •  星月不相逢
    2020-12-11 02:36

    No, rest parameters cannot have a default initialiser. It is not allowed by the grammar because the initialiser would never be run - the parameter always gets assigned an array value (but possibly an empty one).

    What you want to do could be achieved by either

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

    or

    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(', ')}`
    

提交回复
热议问题