javascript - 如何检查对象是否仍在窗口中

标签 javascript object

我想检查是否仍声明了扩展对象。

我的一般对象是:

var test = test || {};

这工作正常:

if (('test' in window)){ console.log("test is there!");  };

但是如果我扩展它......

test.hello = "Is this in window?";

以下检查没有给出结果。

if (('test.hello' in window)){ console.log("test.hello shout be there!");  };

如何检查 test.hello 是否已声明?

最佳答案

窗口上的属性是test。所引用的对象有一个名为hello的属性。

所以你可以像这样做你正在谈论的事情:

if ('test' in window && 'hello' in test){ console.log("test.hello shout be there!");  };

如果 testhello 不可能是 falsey,您可以更有效地做到这一点(in有点慢,尽管你必须在循环中执行数百万次才能关心)并且不那么尴尬:

if (window.test && test.hello){ console.log("test.hello shout be there!");  };
// or
if (window.test && window.test.hello){ console.log("test.hello shout be there!");  };

...但同样,只有当 hello 不能为 false 时才有效(我们知道 test 不是 falsey,它是一个非空对象引用) 。 false 值为 0""NaNnullundefined、当然还有false

<小时/>

来自您下面的评论:

But how I get this to run: var testing="test.hello"; window[testing]=window[testing]&&console.log("testing there")

为此,您必须拆分 . 上的字符串,然后 checkin 循环。函数可能是最好的:

function check(obj, str) {
    return str.split(".").every(function(part) {
        if (part in obj) {
            // The current object has the current part, grab the
            // thing it refers to for use in the next loop
            obj = obj[part];
            return true;
        }
        return false;
    });
}

它使用 ES5 的 Array#every 函数,该函数在 ES5 之前的引擎上是可调整的。 check 函数适用于任意深度,而不仅仅是两个级别。

完整示例:Live Copy

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>Example</title>
</head>
<body>
<script>
  (function() {
    "use strict";

    window.test = {hello: "testing"};

    display("Should be true: " + check(window, "test.hello"));
    display("Should be false: " + check(window, "foo.hello"));
    display("Should be false: " + check(window, "test.foo"));

    window.foo = {
      bar: {
        baz: {
          test: "foo.bar.baz.test"
        }
      }
    };

    display("Should be true: " + check(window, "foo.bar.baz.test"));

    function check(obj, str) {
        return str.split(".").every(function(part) {
            if (part in obj) {
                obj = obj[part];
                return true;
            }
            return false;
        });
    }

    function display(msg) {
      var p = document.createElement('p');
      p.innerHTML = String(msg);
      document.body.appendChild(p);
    }
  })();
</script>
</body>
</html>

关于javascript - 如何检查对象是否仍在窗口中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25347617/

相关文章:

javascript - Ecma-262 (EcmaScript 5) 将如何帮助您?

javascript - 解构 JSON 对象

javascript - 如何理解 document.queryselector 中的转义字符?

java - 如何用 .so 文件打包所有需要的库 linux

javascript - 如何动态遍历 JSON 数据并进行更改..?

javascript - jQuery 词频计数器

javascript - super Backbone

Java - 使用数组作为参数实例化对象

javascript - 在 Canvas 中同时移动一组对象

object - 如何在不进行任何缩放的情况下显示 SVG