如何在 JavaScript 中实现保护子句?
我想保护我的函数免受空值的影响,并且仅在存在“已定义”值时才继续。
查看之后 围绕建议将双倍等于未定义的解决方案:if (something == undefined)
。此解决方案的问题在于您可以声明未定义的变量。
所以我当前的解决方案是检查 null if(something == null)
这隐式检查未定义。如果我想捕获附加错误值,我会检查 if(something)
。
请参阅此处的测试: http://jsfiddle.net/AV47T/2/
现在我在这里错过了一些东西?
马蒂亚斯
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.
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)
.
See tests here: http://jsfiddle.net/AV47T/2/
Now am I missing something here?
Matthias
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
标准的 JS 防护是:
!x
将捕获任何undefined
、null
、false
、0< /code>,或空字符串。
如果你想检查一个值是否有效,那么你可以这样做:
在这一部分中,如果 x 是任何 但是
未定义,则执行该块code>、
null
、false
、0
或空字符串。The standard JS guard is:
!x
will catch anyundefined
,null
,false
,0
, or empty string.If you want to check if a value is valid, then you can do this:
In this piece, the block is executed if x is anything but
undefined
,null
,false
,0
, or empty string.据我所知,防止真正未定义变量(意味着变量名从未在任何地方定义过)的唯一安全方法是检查
typeof
:任何其他操作(包括
if (!_someUndefinedVarName)
)都会失败。基本示例: http://jsfiddle.net/yahavbr/Cg23P/
删除第一个块,您就可以了将得到:
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
:Anything else (including
if (!_someUndefinedVarName)
) will fail.Basic example: http://jsfiddle.net/yahavbr/Cg23P/
Remove the first block and you'll get:
三元来救援!
Ternary to the rescue !
最近才发现使用“&&”作为 JS 中的守卫操作员。不再有 If 语句!
Only recently discovered using '&&' as a guard operator in JS. No more If statements!