如何显式地将“未定义”传递给函数,尝试回退到默认值?

问题描述 投票:0回答:1

假设我有一个名为

printInt
的函数。

void printInt({int v = 0}) {
  print(v);
}

我从一些 JSON 映射对象中读取了整数

v

void main(){
  ...
  int v = someJSONMap['v']; // i don't know whether v is null

  // i want to do something like this:
  //    (which not valid in dart)
  //    printInt(v: v == null ? undefined : v);
}

我无法改变

printInt
(不属于我),而且我不想写这样的代码,因为实际情况要复杂得多。

// i don't want to write like this:
if(v == null){
  print();
}else{
  print(v);
}

上述问题有其他解决方案吗?

flutter dart
1个回答
0
投票

在 JavaScript 中,当您希望函数参数回退到其默认值时,可以显式地将

undefined
传递给该参数。这将触发函数定义中指定的默认值。这是一个例子来说明这一点:

function greet(name = 'Guest') {
  console.log(`Hello, ${name}!`);
}

// Calling the function without arguments
greet(); // Output: Hello, Guest!

// Explicitly passing undefined
greet(undefined); // Output: Hello, Guest!

// Passing a specific value
greet('Alice'); // Output: Hello, Alice!

在此示例中:

  • greet
    函数有一个默认参数
    name
    ,默认值为
    'Guest'
  • 当不带任何参数调用函数时,它使用默认值。
  • 当显式传递
    undefined
    时,该函数也使用默认值。
  • 当传递特定值时,它将覆盖默认值。

此方法可确保每当传递

undefined
时都使用默认值,使您的函数调用更加灵活和可预测。

© www.soinside.com 2019 - 2024. All rights reserved.