JavaScript中的默认参数

发布于 2025-01-18 19:59:55 字数 405 浏览 0 评论 0原文

我想创建一个具有默认参数的函数,但我想使用一个默认参数,然后为下一个参数使用自定义值。例如,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

╰ゝ天使的微笑 2025-01-25 19:59:55
function greet(name, greeting = 'Hey', question = 'How are you?') {
    console.log(`${greeting}, ${name}! ${question}`);
  }

greet('Jack',undefined , 'You good?');

function greet(name, greeting = 'Hey', question = 'How are you?') {
    console.log(`${greeting}, ${name}! ${question}`);
  }

greet('Jack',undefined , 'You good?');

离去的眼神 2025-01-25 19:59:55

您可以为第二个参数传递undefined。它应该按照您的预期工作。

greet('Jack', undefined, 'You good?');

You can pass undefined for the second param. It should work as you expect it to be.

greet('Jack', undefined, 'You good?');
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文