2012-11-28 16 views
26

Questo codice è buono?jQuery/Javascript code check, se non indefinito

var wlocation = $(this).closest('.myclass').find('li a').attr('href'); 
if (wlocation.prop !== undefined) { window.location = wlocation; } 

o devo fare

var wlocation = $(this).closest('.myclass').find('li a').attr('href'); 
if (wlocation.prop !== "undefined") { window.location = wlocation; } 

risposta

65

mi piace questo:

if (wlocation !== undefined) 

Ma se si preferisce il secondo modo wouldn' essere come hai postato Sarebbe:

if (typeof wlocation !== "undefined") 
+1

wlocation è solo una stringa (il valore dell'attributo href) in modo che non ha alcuna proprietà prop ... – Bruno

+0

Grazie, corretto! – Diego

+0

Grazie mille ragazzi. – Jeremy

2

si potrebbe usare semplicemente:

var wlocation = $(this).closest('.myclass').find('li a').attr('href'); 
if (wlocation !== undefined) { window.location = wlocation; } 
10

Io generalmente come la versione abbreviata:

if (!!wlocation) { window.location = wlocation; } 
+2

+1 Davvero bello, non conoscevo il comando '!!' per 'not-undefined'. –

+1

@MichelAyres '!!' non è uno speciale * operatore * o "non indefinito" ... è fondamentalmente due operatori non uno dopo l'altro, ad esempio; '!! undefined => not (not indefinito) => not (true) => false' – Christian