jQuery / Javascript 代码检查,如果不是未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13607712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery / Javascript code check, if not undefined
提问by Jeremy
Is this code good?
这段代码好吗?
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== undefined) { window.location = wlocation; }
or should I do
或者我应该做
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== "undefined") { window.location = wlocation; }
回答by Diego
I like this:
我喜欢这个:
if (wlocation !== undefined)
But if you prefer the second way wouldn't be as you posted. It would be:
但是,如果您更喜欢第二种方式,则不会像您发布的那样。这将是:
if (typeof wlocation !== "undefined")
回答by jeremy
I generally like the shorthand version:
我通常喜欢速记版本:
if (!!wlocation) { window.location = wlocation; }
回答by Bruno
$.fn.attr(attributeName)returns the attribute value as string, or undefinedwhen the attribute is not present.
$.fn.attr(attributeName)将属性值作为字符串返回,或者undefined当属性不存在时。
Since "", and undefinedare both falsy(evaluates to false when coerced to boolean) values in JavaScript, in this case I would write the check as below:
由于"", 和在 JavaScriptundefined中都是假的(当强制为布尔值时计算为假)值,在这种情况下,我将编写如下检查:
if (wlocation) { ... }

