JavaScript中的默认参数
我想创建一个具有默认参数的函数,但我想使用一个默认参数,然后为下一个参数使用自定义值。例如,
function greet(name, greeting = 'Hey', question = 'How are you?') {
console.log(`${greeting}, ${name}! ${question}`);
}
greet('Jack', , 'You good?'); // tried this, doesn't work :(
如果我想说“嘿,Jack!你好吗?”,我使用第一个参数的默认值和默认值,但不使用第二个参数,该怎么办?我尝试过在函数调用中的逗号之间不加任何内容来调用该函数。有没有一种方法可以在 JS 中执行此操作,而无需显式地将定义的默认值“Hey”传递给已分配默认值的参数?
I want to create a function with default params, but I want to use one default param and then use a custom value for the following one. For instance,
function greet(name, greeting = 'Hey', question = 'How are you?') {
console.log(`${greeting}, ${name}! ${question}`);
}
greet('Jack', , 'You good?'); // tried this, doesn't work :(
What if I wanted to say, "Hey, Jack! You good?", where I use the default for the first param with a default value, but not the second? I have tried calling the function with nothing between the commas in the function call. Is there a way to do this in JS without explicitly passing 'Hey', the defined default value, to the param that has a default already assigned?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以为第二个参数传递
undefined
。它应该按照您的预期工作。You can pass
undefined
for the second param. It should work as you expect it to be.