JavaScript 变量 === 未定义无效

JavaScript variable === undefined not working

我有函数:

isset = function(obj){
  alert(obj !== undefined);
 }

然后当我执行 isset(defined_variable)defined_variable 已声明,警告框显示 true 但是当我执行 isset(undefined_variable)undefined_variable 尚未声明,警告框根本不显示,而我希望警告框显示 false。我究竟做错了什么?我试过使用 typeof 但结果是一样的。

but when I do isset(undefined_variable) where udefined_variable has not been declared, the alert box does not show at all, while I expected the alert box to show false

因为它在您的控制台中抛出一个错误(检查您的控制台),您正在比较的变量未定义。

Uncaught ReferenceError: 'c' is not defined

我试过 isset( c ) 并且 c 没有先声明

那是因为 undefined 和 undeclared 是有区别的。

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

当你取消引用一个未声明的变量时(意味着你尝试使用一个以前从未写过的符号),你会得到一个 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;
}

我们不能真正在 isset 中使用 typeof,这很可悲,因为它很方便,因为它不会在从未声明变量时抛出 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