在PHP中,你可以做if(isset($array['foo'])) { ... }
。在JavaScript中,您经常使用if(array.foo) { ... }
来做同样的事情,但这并不是完全相同的语句。如果array.foo
确实存在,但为false
或0
(也可能是其他值),则该条件的计算结果也将为false。
在JavaScript中,什么是PHP的isset
的完美等价物?
在更广泛的意义上,一个关于JavaScript处理不存在的变量、没有值的变量等的通用、完整的指南将是很方便的。
发布于 2010-02-17 22:59:43
if (!('foo' in obj)) {
// not set.
}
发布于 2013-08-21 21:23:18
//
// tring to reference non-existing variable throws ReferenceError
// before test function is even executed
//
// example, if you do:
//
// if ( isset( someVar ) )
// doStuff( someVar );
//
// you get a ReferenceError ( if there is no someVar... )
// and isset fn doesn't get executed.
//
// if you pass variable name as string, ex. isset( 'novar' );,
// this might work:
//
function isset ( strVariableName ) {
try {
eval( strVariableName );
} catch( err ) {
if ( err instanceof ReferenceError )
return false;
}
return true;
}
//
//
发布于 2014-06-22 00:33:59
这个简单的解决方案有效,但不适用于深度对象检查。
function isset(str) {
return window[str] !== undefined;
}
https://stackoverflow.com/questions/2281633
复制相似问题