我做了一个循环,以检查另一个对象中是否不存在某个键。一旦满足此条件,它将停止并重定向到某个URL。我使循环正常工作,但是我的问题是,一旦满足条件,就可以。仍然继续为其余项目循环。意味着它永远不会停止,并且会创建某种infite循环。我如何确定是否满足条件(如果)。循环停止。
必填资源:
资源: (第一次为空)
循环:
// 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`);
}
});
答案 0 :(得分:2)
您可以使用some()
数组方法,例如:
const found = requiredResource.some(({name}) => Object.keys(resources).indexOf(name) > -1)
if (!found) {
window.location.assign(`getspecificresource.com`);
} else {
// Key from resource is matching the required key. you can continue
//continue
}
编辑:
根据讨论,您可以像这样更新代码,以实现所需的行为,因为我们无法脱离forEach
循环:
requiredResource.some((item) => {
// Check if there are resources, if not go get them
if (resources.length !== 0) {
// Resources are filled with 2 examples
Object.keys(resources).some(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`);
return true;
} else {
// Key from resource is matching the required key. you can continue
//continue
return false;
}
});
return false;
} else {
// get resources
window.location.assign(`getalistwithresources.com`);
return true;
}
});
只需将some()
与return true
一起使用即可跳出此处的循环。
答案 1 :(得分:0)
您可以尝试这样的事情...
let obj = {
'a': 1,
'b': 2,
'c': 3
}
console.log(obj.a)
Object.keys(obj).some(x=>{
console.log(obj[x])
return obj[x]==2
})
并使用return语句中断循环,这有帮助吗?