简体   繁体   English

JavaScript:检查是否存在变量或对象

[英]JavaScript: Check to see if a variable or object exists

I have a function to return if a variable/object is set or not: 我有一个函数返回是否设置了变量/对象:

function isset() {
    var a = arguments, l = a.length;
    if (l === 0) { console.log("Error: isset() is empty"); }
    for (var i=0; i<l; i++) {
        try {
            if (typeof a[i] === "object") {
                var j=0;
                for (var obj in a[i]) { j++; }
                if (j>0) { return true; }
                else { return false; }
            }
            else if (a[i] === undefined || a[i] === null) { return false; }
        }
        catch(e) {
            if (e.name === "ReferenceError") { return false; }
        }
    }
    return true;
}

For example, this works: 例如,这有效:

var foo;
isset(foo);        // Returns false
foo = "bar";
isset(foo);        // Returns true
foo = {};
isset(foo);        // Returns false
isset(foo.bar);    // Returns false
foo = { bar: "test" };
isset(foo);        // Returns true
isset(foo.bar);    // Returns true

Here is the problem... if foo is never set to begin with, this happens: 这是问题所在...如果foo从未设置为开始,则会发生这种情况:

// foo has not been defined yet
isset(foo); // Returns "ReferenceError: foo is not defined"

I thought I could use try/catch/finally to return false if error.name === "ReferenceError" but it isn't working. 我认为如果error.name ===“ ReferenceError”,我可以使用try / catch / finally返回false,但是它不起作用。 Where am I going wrong? 我要去哪里错了?


Edit: 编辑:

So the answer below is correct. 因此,下面的答案是正确的。 As I expected, you cannot access an undefined variable or trap it with try/catch/finally (see below for an explanation). 如我所料,您无法访问未定义的变量或使用try / catch / finally捕获该变量(请参阅下文以获取解释)。

However, here is a not so elegant solution. 但是,这不是一个很好的解决方案。 You have to pass the name of the variable in quotes, then use eval to do the checking. 您必须在引号中传递变量的名称,然后使用eval进行检查。 It's ugly, but it works: 很难看,但是可以用:

// Usage: isset("foo"); // Returns true or false
function isset(a) {
    if (a) {
        if (eval("!!window."+a)) {
            if (eval("typeof "+a+" === 'object'")) { return eval("Object.keys("+a+").length > 0") ? true : false; }
            return (eval(a+" === undefined") || eval(a+" === null") || eval(a+" === ''")) ? false : true;
        }
        else { return false; }
    }
    else { console.log("Empty value: isset()"); }
}

And just to follow up some more, I cleaned up the original function at the very top. 为了进一步了解更多信息,我在最顶层清理了原始功能。 It still has the same problem where if the variable doesn't exist you get a ReferenceError, but this version is much cleaner: 它仍然存在相同的问题,如果不存在该变量,您将得到ReferenceError,但是此版本更加干净:

// Usage: isset(foo); // Returns true or false if the variable exists.
function isset(a) {
    if (a) {
        if (typeof a === "object") { return Object.keys(a).length > 0 ? true : false; }
        return (a === undefined || a === null || a === "") ? false : true;
    }
    else { console.log("Empty value: isset()"); }
}

You just can't do that type of check with a function. 您只是无法通过函数执行这种类型的检查。 In order to pass the variable, it needs to exist, so it will fail before your code can run. 为了传递变量,它必须存在,因此它将在代码运行之前失败。

When you call it on the undeclared variable, you're attempting to resolve the value of the identifier in the argument position. 当您在未声明的变量上调用它时,您尝试解析参数位置的标识符值。

//     v----resolve identifier so it can be passed, but resolution fails
isset(foo);

And of course, it doesn't exist, so the ReferenceError is thrown. 当然,它不存在,因此抛出了ReferenceError

JavaScript doesn't have pointers, so there's nothing like a nil pointer that can be passed in its place. JavaScript没有指针,因此没有什么可以代替nil指针的了。

You cannot pass a identifier that hasn't been initialised. 您不能传递尚未初始化的标识符。 You could pass a string, and an object to test, like the following: 您可以传递一个字符串和一个要测试的对象,如下所示:

function isset(str, obj) {
  return obj[str] ? true : false;
}

isset("foo", window); // >>> false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM