我有这个功能:
isset = function(obj){
alert(obj !== undefined);
}
然后当我isset(defined_variable)
宣布defined_variable
时,警告框会显示 true ,但当我isset(undefined_variable)
udefined_variable
时没有声明,警报框根本没有显示,而我希望警告框显示 false 。我究竟做错了什么?我尝试过使用typeof
但结果是一样的。
答案 0 :(得分:4)
那是因为未定义和未声明之间存在差异。
var foo; // foo is undefined.
// bar is undeclared.
console.log(foo === undefined); // true
try {
console.log(bar === undefined);
} catch (e) {
console.error('I had an error!'); // gets invoked.
}
foo = 'something';
console.log(foo === undefined); // false
答案 1 :(得分:1)
但是当我执行isset(undefined_variable)时,udefined_variable有 没有声明,警报框根本没有显示,而我 预计警告框显示错误
因为它在您的控制台(检查您的控制台)中抛出了一个错误,即您正在比较的此变量未定义。
未捕获的ReferenceError:' c'未定义
我尝试使用isset( c )
并且c
未首先声明
答案 2 :(得分:1)
当您取消引用未声明的变量(意味着您尝试使用之前从未写过的符号)时,您会得到Reference error
。
有几种方法可以解决这个问题,但是你无法确定javascript中的局部变量是什么。因此,您的问题只能针对全局变量或给定的范围对象动态解决。
如果您在浏览器上下文中,则可以使用window
作为前缀(有关更多上下文,请参阅this SO answer about global object in javascript)
这不会修改您的isset
功能代码:
isset(window.undefined_variable)
还有另一种方法,需要isset
函数更改,但使用相同的原则(仍然在浏览器上下文中):
isset('undefined_variable_name_wrawppped_in_a_string')
function isset(name) {
return name in window;
}
我们无法真正在typeof
中使用isset
,这很难过,因为它很方便,因为它从未在声明变量时抛出Reference Error
。我们仍然可以使用一种形式的eval来做,但由于我不希望我们去那里,我不会实现它。
但是现在,如果你想检查几个嵌套属性怎么办?
function isset (memoryPath, root) {
var nodeNames = memoryPath.split('.');
var expectedDepthReached = nodeNames.length;
var depthReached = 0;
var nodeName;
var node = root;
// we are gonna read it from left to right
// using Array.prototype.pop()
// reversing it will alow us to do so
nodeNames.reverse();
do {
nodeName = nodeNames.pop();
node = node[nodeName];
if (node) {
depthReached++;
}
} while (node);
return depthReached === expectedDepthReached;
}
一个例子:
window.myGlobals = {
path: {
to: {
a: {
variable: true
}
}
}
};
isset('myGlobals.path.to.a.variable', window), // true
isset('myGlobals.path.foo', window) // false