【发布时间】:2020-06-18 04:57:30
【问题描述】:
我做了一个循环来检查一个键是否不存在于另一个对象中。一旦此条件为真,它应该停止并重定向到某个 URL。我让循环工作,但我的问题是,只要条件得到满足。它仍然继续循环剩余的项目。这意味着它永远不会停止并创建某种无限循环。我如何确定是否满足条件(如果)。循环停止。
所需资源:
资源: (第一次为空)
循环:
// For every requiredResource check if it exist in the resources. (right now it is one)
requiredResource.forEach((item: any) => {
// Check if there are resources, if not go get them
if(resources.length !== 0){
// Resources are filled with 2 examples
Object.keys(resources).forEach(value => {
//if the required is not in there, go get this resource and stop the loop
if(value !== item.name){
// Go get the specific resource that is missing
window.location.assign(`getspecificresource.com`);
} else {
// Key from resource is matching the required key. you can continue
//continue
}
});
} else {
// get resources
window.location.assign(`getalistwithresources.com`);
}
});
【问题讨论】:
-
简单的
Object.keys(yourObject).indexOf("key_you_are_checking_for") !== -1,不需要forEach。 -
您可以使用
Array.find()代替forEach(),但我不明白显示的代码如何创建无限循环。 -
如果这是一个专用功能(即没有其他事情可以做),那么您可以插入一个 [return] 语句。
标签: javascript loops object foreach