2008年9月12日 星期五

undefined / null in JavaScript

In JavaScript null is an object. undefined is used for things that don't exist. The DOM returns null for almost all cases where it fails to find some structure in the document, but in JavaScript itself undefined is the value used.

null and undefined are not strictly equivalent. If you really want to check for null, do:

if (varname == null) // with casting
if (varname === null) // without casting (i.e. same value, same type)

If you want to check if a variable exist

if (typeof(varname) != 'undefined')

The variable exists but you want to know if there's any value stored in it:

if (varname != undefined)

Check if a member variable exists (independent of whether it has been assigned a value or not) :

if ('varname' in object) // With inheritance
if (object.hasOwnProperty('varname')) // Without inheritance


摘自:http://blog.jails.fr/index.php?post/2007/08/01/undefined-/-null-in-JavaScript

沒有留言:

wibiya widget