假设我有一个名为
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);
}
上述问题有其他解决方案吗?
在 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
时都使用默认值,使您的函数调用更加灵活和可预测。