我可以这样做来检查全局变量是否已定义:
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,因为它们并不存在。这是另一个系统,它通过异步操作向页面注入一些东西,因此我不知道该操作何时完成。但我只能在那之后开始我的操作。这就是为什么我需要检查整个层次结构是否存在的原因。
reduce
使用不正确,你永远不能在其中返回任何内容,因此anchor
将始终是undefined
。globalVariableForReducingInWaitAndRun
从未被声明(使用let
或var
),这是有意为之吗?我认为它有点过于复杂,可以大大简化。 - blexhuman
,而不是head
?这是糟糕的设计。 - malifa