我有一个数组 arr=[{key: 'first'},{key: 'second'} ...]
,我想遍历该数组并检查元素是否具有一个特定的键存在并做一些事情。
arr.forEach(element => {
if(element.key === 'first') {
// do something
} else {
// do something else
}
if(element.key === 'second') {
// do something
} else {
// do something else
}
});
问题是,当它遍历数组时,它首先看到 'first'
然后它遍历 if()
语句,但它也遍历
语句,因为它没有找到它,当 'second'
项的 else()foreach
遍历数组中的其他项时也是如此。我不知道如何让它一次遍历数组并适本地设置 if() else()
。因此,当它找到 'first'
时,我希望它只执行该项目的 if()
而不是其他项目的 else()
。我希望你明白。提前致谢!
编辑:我在这段代码背后的逻辑是,当我调用数据库并找到该数组时,如果该数组中没有 'firstExercise'
,那么它应该将它添加到该数据库(我正在使用firebase 所以在 else()
我调用 db 来创建那个练习),如果数组中有 'firstExercise'
什么也不做。很抱歉没有澄清这一点。
Edit2:这是我的原始代码:
res.forEach(element => {
if (this.numbOfFinished === 1) {
if (element.key === 'firstExercise') {
console.log('has')
} else {
awardName = 'firstExercise'
this.homeService.addAward(this.userId, awardName).then(() => {
this.awardName = 'firstExercise';
this.awarded = true;
});
}
}
});
if (this.numbOfFinished === 5) {
if (element.key === 'fifthExercise') {
console.log('has')
} else {
awardName = 'fifthExercise'
this.homeService.addAward(this.userId, awardName).then(() => {
this.awardName = 'fifthExercise';
this.awarded = true;
});
}
}
});
最佳答案
我个人喜欢创建数组来建立键和函数之间的关系。所以我可以迭代并调用正确的。
在这个解决方案中,我喜欢这个解决方案而不是使用 switch/case
或 if/else
森林,因为你可以应用自动处理,而且你可以很容易地做到进化。
const mapKeyFunc = [{
key: 'first',
func: async(x) => {
console.log('Do something for key first');
// here you can perform an async request and modify `this`
},
}, {
key: 'second',
func: async(x) => {
console.log('Do something for key second');
// here you can perform an async request and modify `this`
},
}];
const doStuff = async(arr) => {
for (let i = 0; i < arr.length; i += 1) {
const mapElement = mapKeyFunc.find(x => x.key === arr[i].key);
await mapElement.func.call(this, arr[i]);
}
};
const arr = [{
key: 'first',
otherStuff: 0,
}, {
key: 'second',
otherStuff: 42,
}];
doStuff(arr).then(() => {}).catch(e => console.log(e));
如果不需要处理是同步的,这里我们有一个异步的方法
const mapKeyFunc = [{
key: 'first',
func: async(x) => {
console.log('Do something for key first');
// here you can perform an async request and modify `this`
},
}, {
key: 'second',
func: async(x) => {
console.log('Do something for key second');
// here you can perform an async request and modify `this`
},
}];
const doStuff = async(arr) => {
await Promise.all(arr.map(x => mapKeyFunc.find(y => y.key === x.key).func.call(this, x)));
};
const arr = [{
key: 'first',
otherStuff: 0,
}, {
key: 'second',
otherStuff: 42,
}];
doStuff(arr).then(() => {}).catch(e => console.log(e));
关于javascript - 如果在foreach中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50528628/