gpt4 book ai didi

javascript - 如何为中间变量参数使用 ECMAScript 6 默认值功能?

转载 作者:行者123 更新时间:2023-11-30 08:27:57 24 4
gpt4 key购买 nike

在阅读 ES6 的新特性时,我发现了定义默认值的好方法:

In ECMAScript 6 we can add default values to the parameters of a function. This means that if we don’t pass in arguments later in the function call, the default parameters will be used. In ES5 the default values of parameters are always set to undefined, so the new possibility to set them to whatever we want is definitely a great enhancement of the language.

所以像这样使用它非常简单:

function f(p1=1, p2=2, p3=3, p4=4, p5=5){
return "{p1: " + p1 + ", p2: " + p2 + ", p3: " + p3 + ", p4: " + p4 + ", p5: " + p5 + "}";
}
var test = f();
console.log( test );
//outputs: {p1: 1, p2: 2, p3: 3, p4: 4, p5: 5}

我想知道我们如何使用这个特性来做这样的事情:

function f(p1=1, p2, p3, p4, p5=5){
return "{p1: " + p1 + ", p2: " + p2 + ", p3: " + p3 + ", p4: " + p4 + ", p5: " + p5 + "}";
}
var test = f(,20, 30, 40,); //which is not correct

所以当我执行它时,我得到了这个结果:

{p1: 1, p2: 20, p3: 30, p4: 40, p5: 5}

最佳答案

传递 undefined 与不传递任何内容相同(关于默认值):

f(undefined, 20, 30, 40);

不过,最好只为函数中最右边的参数提供默认值:

function f(p2, p3, p4, p1=1, p5=5) { … }
f(20, 30, 40);

关于javascript - 如何为中间变量参数使用 ECMAScript 6 默认值功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42208133/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com