[英]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. 我希望保护我的函数不受null-ish值的影响,只有在存在“已定义”值时才会继续。
After looking around the solutions suggested to double equal to undefined: if (something == undefined)
. 之后找 周围的解决方案,建议增加一倍等于未定义:
if (something == undefined)
。 The problem with this solution is that you can declare an undefined variable. 此解决方案的问题是您可以声明未定义的变量。
So my current solution is to check for null if(something == null)
which implicetly checks for undefined. 所以我目前的解决方案是检查null
if(something == null)
,这意味着检查undefined。 And if I want to catch addionalty falsy values I check if(something)
. 如果我想捕捉附加值假值,我检查
if(something)
。
See tests here: http://jsfiddle.net/AV47T/2/ 请参阅此处的测试: http : //jsfiddle.net/AV47T/2/
Now am I missing something here? 我现在错过了什么吗?
Matthias 马蒂亚斯
The standard JS guard is: 标准的JS守卫是:
if (!x) {
// throw error
}
!x
will catch any undefined
, null
, false
, 0
, or empty string. !x
将捕获任何undefined
, null
, false
, 0
或空字符串。
If you want to check if a value is valid , then you can do this: 如果要检查值是否有效 ,则可以执行以下操作:
if (Boolean(x)) {
// great success
}
In this piece, the block is executed if x is anything but undefined
, null
, false
, 0
, or empty string. 在这一块,如果x是什么,但在执行块
undefined
, null
, false
, 0
,或空字符串。
-tjw -tjw
The only safe way that I know of to guard against really undefined variables (meaning having variable name that were never defined anywhere) is check the typeof
: 我知道防止真正未定义的变量(意味着具有从未在任何地方定义的变量名称)的唯一安全方法是检查
typeof
:
if (typeof _someUndefinedVarName == "undefined") {
alert("undefined");
return;
}
Anything else (including if (!_someUndefinedVarName)
) will fail. 其他任何东西(包括
if (!_someUndefinedVarName)
)都会失败。
Basic example: http://jsfiddle.net/yahavbr/Cg23P/ 基本示例: http : //jsfiddle.net/yahavbr/Cg23P/
Remove the first block and you'll get: 删除第一个块,你会得到:
_someUndefinedVarName is not defined
_someUndefinedVarName未定义
Only recently discovered using '&&' as a guard operator in JS. 直到最近才发现在JS中使用'&&'作为保护运算符。 No more If statements!
没有更多If声明!
var data = {
person: {
age: 22,
name: null
}
};
var name = data.person.name && doSomethingWithName(data.person.name);
Ternary to the rescue ! 三元救援!
(i) =>
i == 0 ? 1 :
i == 1 ? 2 :
i == 2 ? 3 :
null
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.