gpt4 book ai didi

javascript - 如何在全局范围内动态检查嵌套对象的存在?

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

我可以do this检查是否定义了全局变量:

if (window.globalVariableName) {
// it's defined, now it's safe to work with it
}

现在我有一个嵌套层次结构,只有当每个嵌套对象都定义到叶时我才应该处理它,并且这个嵌套层次结构可以是任何东西。例如我可以有这两个层次结构:

human.head.mouth.lips.upperLip.color

building.firstFloor.hallway.lastRoom.chair.density

我想检查是否存在所有嵌套,直至叶值,并且仅当定义了包括叶在内的整个层次结构时,才执行某些操作。换句话说,我希望能够动态地创建这个静态代码:

if (window.human.head.mouth.lips.upperLip.color) {
// now I know human is defined, and head, and mouth, and ... and up to color
}

我试过这段代码,但它不起作用:

function checkThenRun(targetToWaitFor, callback) {
if (typeof callback !== "function") {
console.error('Callback for checkThenRun should be a function');
return;
}
if (targetToWaitFor.indexOf('.') > -1) {
targetToWaitFor.split('.').reduce(function (anchor, recursion) {
if (anchor) {
globalVariableForReducingInWaitAndRun = window[anchor];
if (globalVariableForReducingInWaitAndRun) {
globalVariableForReducingInWaitAndRun = globalVariableForReducingInWaitAndRun[recursion];
}
}
else {
globalVariableForReducingInWaitAndRun = globalVariableForReducingInWaitAndRun[recursion];
}
});
if (!globalVariableForReducingInWaitAndRun) {
console.warn('checkThenRun waiting for ' + targetToWaitFor + '...');
setTimeout(function () {
checkThenRun(targetToWaitFor, callback);
}, 500);
return;
}
}
if (typeof window[targetToWaitFor] === "undefined") {
console.warn('checkThenRun waiting for ' + targetToWaitFor + '...');
setTimeout(function () {
checkThenRun(targetToWaitFor, callback);
}, 50)
return;
}
callback();
}

这是使用示例:

checkAndRun('human.head.mouth.lips.upperLip.color', function() {
// now I know this hierarchy is created, I can change color for example
});

更新:

我正在开发一个基于混搭架构的系统。网页由许多不同的来源填充。我不能也无权访问这些外部资源。我不能要求他们为我提供 API,因为他们不存在。这是另一个工作的系统,并通过异步操作向页面注入(inject)一些东西,因此我不知道该操作何时完成。但只有在那之后我才能开始我的手术。这就是为什么我需要检查整个层次结构是否存在。

最佳答案

您似乎需要等待某些(外部)脚本将内容添加到全局范围。通常,有办法避免这种情况。大多数库允许您在某些(异步)操作完成时定义回调。您真的应该检查您尝试使用的脚本/库的文档。如果实在没有别的办法,可以使用下面的方法来等待变量为真:

function waitUntilTruthy(cb) {
return new Promise(resolve => {
const interval = setInterval(() => {
if (cb()) {
clearInterval(interval);
resolve();
}
}, 50);
});
}

waitUntilTruthy(() => window?.human?.head?.mouth?.lips?.upperLip?.color).then(() => {
// variable is defined
});

请注意 optional chaining语法 (a?.b?.c) 将出现在 ECMAScript 2020 中,可能还无法在您的目标运行时(即浏览器和/或 Node.js)中运行。确保检查 compatibility并考虑使用 Babel或 TypeScript 3.7+。看看How to avoid 'cannot read property of undefined' errors?可选链的替代方案。

关于javascript - 如何在全局范围内动态检查嵌套对象的存在?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60811485/

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