这段代码好吗?
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== undefined) { window.location = wlocation; }
或者我应该
var wlocation = $(this).closest('.myclass').find('li a').attr('href');
if (wlocation.prop !== "undefined") { window.location = wlocation; }
答案 0 :(得分:81)
我喜欢这个:
if (wlocation !== undefined)
但是,如果你更喜欢第二种方式不会像你发布的那样。它将是:
if (typeof wlocation !== "undefined")
答案 1 :(得分:12)
我一般喜欢速记版本:
if (!!wlocation) { window.location = wlocation; }
答案 2 :(得分:4)
$.fn.attr(attributeName)将字符串返回属性值,或者当属性不存在时返回undefined
。
由于""
和undefined
在JavaScript中都是 falsy (在强制布尔值时评估为false)值,在这种情况下我会将检查写成如下:
if (wlocation) { ... }