在PHP中你可以做到if(isset($array['foo'])) { ... }.在JavaScript中,您经常使用if(array.foo) { ... }相同的方法,但这不是完全相同的语句.如果array.foo确实存在,条件也将评估为false,但是false或者0(也可能是其他值).
issetJavaScript 中PHP的完美等价物是什么?
从更广泛的意义上讲,JavaScript处理不存在的变量,没有值的变量等的一般完整指南会很方便.
如何检查是否以跨浏览器的方式定义了JavaScript变量?
在使用FireBug日志记录编写一些JavaScript时遇到了这个问题.我写了一些代码如下:
function profileRun(f) {
// f: functions to be profiled
console.profile(f.constructor);
f();
console.profileEnd(f.constructor);
}
Run Code Online (Sandbox Code Playgroud)
它在FireFox/FireBug中工作正常,但它在IE8 RC1中报告错误.所以,我想检查执行环境中是否存在控制台变量.
下面的代码在FireFox中工作正常,但在IE8 RC1中没有.
function profileRun(f) {
if (console != undefined) {
console.profile(f.constructor);
}
f();
if (console != undefined) {
console.profileEnd(f.constructor);
}
}
Run Code Online (Sandbox Code Playgroud)
但是,如果我这样做的话.它适用于IE8 RC1.为什么?
function profileRun(f) {
if (window.console != undefined) {
console.profile(f.constructor);
}
f();
if (window.console != undefined) {
console.profileEnd(f.constructor);
}
}
Run Code Online (Sandbox Code Playgroud)
是否有任何跨浏览器的方式来检查它?