gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 12:02:34 25 4
gpt4 key购买 nike

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

我的一般对象是:

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com