hip*_*ail 12 javascript null idioms undefined coercion
在类型和类似事物之间存在相当多的JavaScript惯用语.
!可什么falsey转换为布尔true,!!可以什么falsey转换为真正的布尔值false,+可以转换true,false或者一个字符串代表一个数字,实际人数,等等.
是否有类似的东西转换undefined为null?
现在我正在使用三元,? :但知道我是否错过了一个有用的技巧会很酷.
好吧,让我设想一个例子......
function callback(value) {
return value ? format(value) : null;
}
Run Code Online (Sandbox Code Playgroud)
callback由第三方代码调用,有时会通过undefined.
第三方代码可以处理null被传回,但不能undefined.format()也是第三方,无法处理被传递undefined或null.
Hug*_*lva 10
undefined || null - 或任何虚假|| null - 将返回null
Javascript 现在支持空合并运算符:??. 它可能不是生产就绪的(请参阅支持表),但与 Node 或转译器(TypeScript、Babel 等)一起使用肯定是安全的。
每个MDN ,
空合并运算符 (??) 是一个逻辑运算符,当其左侧操作数为空或未定义时返回其右侧操作数,否则返回其左侧操作数。
就像||当左操作数是falsey,可以提供一个“默认”值,??如果左操作数为空或未定义提供了一个“默认”值。您可以使用它来将 undefined 强制为 null:
// OR operator can coerce 'defined' values
"value" || null; // "value"
0 || null; // null
false || null; // null
"" || null; // null
undefined || null; // null
// The null-coalescing operator will only coerce undefined or null
"value" ?? null; // "value"
0 ?? null; // 0
false ?? null; // false
"" ?? null; // ""
undefined ?? null; // null
Run Code Online (Sandbox Code Playgroud)
基于问题的示例:
function mustNotReturnUndefined(mightBeUndefined) { // can return null
// Substitute empty string for null or undefined
let result = processValue(mightBeUndefined ?? "");
// Substitute null for undefined
return result ?? null;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4413 次 |
| 最近记录: |