如何在JavaScript中实现保护子句? [英] How do you implement a guard clause in JavaScript?
问题描述
我想保护我的函数免受空值影响,并且仅在存在已定义"值的情况下继续操作.
I want to guard my functions against null-ish values and only continue if there is "defined" value.
After looking around the solutions suggested to double equal to undefined: if (something == undefined)
. The problem with this solution is that you can declare an undefined variable.
所以我当前的解决方案是检查null if(something == null)
,这会隐式检查undefined.如果我想捕获其他虚假值,请检查 if(something)
.
So my current solution is to check for null if(something == null)
which implicetly checks for undefined. And if I want to catch addionalty falsy values I check if(something)
.
在此处查看测试: http://jsfiddle.net/AV47T/2/
现在我在这里想念什么吗?
Now am I missing something here?
Matthias
推荐答案
标准的JS保护措施是:
The standard JS guard is:
if (!x) {
// throw error
}
!x
将捕获任何 undefined
, null
, false
, 0
,或空字符串.
!x
will catch any undefined
, null
, false
, 0
, or empty string.
如果要检查值是否为有效,则可以执行以下操作:
If you want to check if a value is valid, then you can do this:
if (Boolean(x)) {
// great success
}
在本段中,如果x为但 undefined
, null
, false
, 0
或空字符串.
In this piece, the block is executed if x is anything but undefined
, null
, false
, 0
, or empty string.
-tjw
这篇关于如何在JavaScript中实现保护子句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!