javascript es6:用例解析rest参数 [英] javascript es6: use case for destructuring rest parameter
问题描述
我刚刚在MDN中看到了一个代码片段,关于如何解析其余参数:
I just saw a code snippet in MDN about destructuring rest parameters like so:
function f(...[a, b, c]) {
return a + b + c;
}
f(1) // NaN (b and c are undefined)
f(1, 2, 3) // 6
f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured)
虽然休息参数的常见用例对我来说非常清楚( function foo(... params){/ * code * /}
)我无法考虑使用其他参数的真实世界用例,就像该代码段中提供的方式一样。相反,我认为在这种情况下,我应该使用一个通用的函数定义:
Although the common use case for rest parameters is very clear to me (function foo(...params){/*code*/}
) I could not think about a real world use case to use rest parameters like the way presented in that code snippet. Instead, I think that in that case, I should just use a common function definition:
function f(a, b, c) {
return a + b + c;
}
f(1) // NaN (b and c are undefined)
f(1, 2, 3) // 6
f(1, 2, 3, 4) // 6 (the fourth parameter is not defined)
推荐答案
您的函数f(a,b,c){...}
确实是写这个的正确方法。它和其余+解构语法之间的唯一区别是,rest参数不会添加到参数个数,即 f.length == 0
。
Your function f(a, b, c) { … }
is indeed the proper way to write this. The only difference between that and the rest+destructuring syntax is that rest parameters do not add to number of parameters, i.e. f.length == 0
.
将数组解构模式作为rest参数的目标确实没有好的用例。仅仅因为语法允许它并不意味着它在某个地方很有用。 MDN示例可能应该更清楚。
There really is no good use case for putting an array destructuring pattern as the target of a rest parameter. Just because the syntax allows it doesn't mean that it's useful somewhere. The MDN example probably should've made that more clear.
这篇关于javascript es6:用例解析rest参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!