我有一个<select>
发送option
的值(在下面列出)。然后将该值传递到React Hook中。这是可行的,但是有没有一种更干燥/更清洁/更有效的方式来处理条件语句?
选择选项
const animals = [
"Cows", "Pigs", "Sheep", "Goats", "Lambs", "Rabbits"
]
功能
const _updateLocationData = (value) => {
var tempLocations = [];
locations.forEach(function(res) {
if (value === "Cows" && res.Cows === "Yes") {
tempLocations.push(res);
}
if (value === "Pigs" && res.Pigs === "Yes") {
tempLocations.push(res);
}
if (value === "Sheep" && res.Sheep === "Yes") {
tempLocations.push(res);
}
if (value === "Goats" && res.Goat === "Yes") {
tempLocations.push(res);
}
if (value === "Lambs" && res.Lamb === "Yes") {
tempLocations.push(res);
}
if (value === "Rabbits" && res.Rabbit === "Yes") {
tempLocations.push(res);
}
});
}
最佳答案
考虑这样的事情:只需确认value
在所需的数组中,然后检查[value]
的res
属性是否等于"Yes"
:
const animals = [
"Cows", "Pigs", "Sheep", "Goats", "Lambs", "Rabbits"
]
const _updateLocationData = (value) => {
var tempLocations = [];
locations.forEach(function(res) {
if (animals.includes(value) && res[value] === "Yes") {
tempLocations.push(res);
}
});
}
关于javascript - 使用JavaScript从forEach响应中检查所有条件的更有效方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59851989/