对于局部变量,使用with localVar === undefined
可以进行检查,因为它们必须已在局部范围内的某个位置定义,否则将不被视为局部变量。
对于不在局部且未在任何地方定义的变量,检查someVar === undefined
将引发异常:Uncaught ReferenceError:j未定义
这是一些代码,这些代码将阐明我在上面所说的内容。请注意内联注释,以进一步明确。
function f (x) {
if (x === undefined) console.log('x is undefined [x === undefined].');
else console.log('x is not undefined [x === undefined.]');
if (typeof(x) === 'undefined') console.log('x is undefined [typeof(x) === \'undefined\'].');
else console.log('x is not undefined [typeof(x) === \'undefined\'].');
// This will throw exception because what the hell is j? It is nowhere to be found.
try
{
if (j === undefined) console.log('j is undefined [j === undefined].');
else console.log('j is not undefined [j === undefined].');
}
catch(e){console.log('Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.');}
// However this will not throw exception
if (typeof j === 'undefined') console.log('j is undefined (typeof(x) === \'undefined\'). We can use this check even though j is nowhere to be found in our source code and it will not throw.');
else console.log('j is not undefined [typeof(x) === \'undefined\'].');
};
如果我们像这样调用上面的代码:
f();
输出将是这样的:
x is undefined [x === undefined].
x is undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
如果我们像这样调用上面的代码(实际上有任何值):
f(null);
f(1);
输出将是:
x is not undefined [x === undefined].
x is not undefined [typeof(x) === 'undefined'].
Error!!! Cannot use [j === undefined] because j is nowhere to be found in our source code.
j is undefined (typeof(x) === 'undefined'). We can use this check even though j is nowhere to be found in our source code and it will not throw.
当您执行如下检查:时typeof x === 'undefined'
,您实际上是在问:请检查该变量x
是否在源代码中的某个位置存在(已定义)。(或多或少)。如果您知道C#或Java,则永远不会进行这种检查,因为如果不存在,则将无法编译。
<==摆弄我==>