我想减少以下代码。这个问题可能非常la脚,对此感到抱歉。 我想用for循环中的一个变量替换顿饭1..10,但是我不确定是否可以在节点js中完成。
function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
if (meals.meal1 != undefined && meals.meal1.activado == "on" && portions.indexOf(meals.meal1.porcion) < 0) { return false; }
if (meals.meal2 != undefined && meals.meal2.activado == "on" && portions.indexOf(meals.meal2.porcion) < 0) { return false; }
if (meals.meal3 != undefined && meals.meal3.activado == "on" && portions.indexOf(meals.meal3.porcion) < 0) { return false; }
if (meals.meal4 != undefined && meals.meal4.activado == "on" && portions.indexOf(meals.meal4.porcion) < 0) { return false; }
if (meals.meal5 != undefined && meals.meal5.activado == "on" && portions.indexOf(meals.meal5.porcion) < 0) { return false; }
if (meals.meal6 != undefined && meals.meal6.activado == "on" && portions.indexOf(meals.meal6.porcion) < 0) { return false; }
if (meals.meal7 != undefined && meals.meal7.activado == "on" && portions.indexOf(meals.meal7.porcion) < 0) { return false; }
if (meals.meal8 != undefined && meals.meal8.activado == "on" && portions.indexOf(meals.meal8.porcion) < 0) { return false; }
if (meals.meal9 != undefined && meals.meal9.activado == "on" && portions.indexOf(meals.meal9.porcion) < 0) { return false; }
if (meals.meal10 != undefined && meals.meal10.activado == "on" && portions.indexOf(meals.meal10.porcion) < 0) { return false; }
return true;
}
答案 0 :(得分:0)
如果膳食仅具有这10种特性,您可能会喜欢
function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
for (const prop in meals) {
const meal = meals[prop];
if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
return false;
}
}
return true;
}
如果您有更多属性,但只想检查这10个属性,您可能会喜欢,
function hasPortion(meals) {
const portions = ["4", "3", "2", "1", "1/8", "1/4", "1/2"];
for (let i = 1; i <= 10; i++) {
const prop = `meal${i}`;
const meal = meals[prop];
if (meal != undefined && meal.activado == "on" && portions.indexOf(meal.porcion) < 0) {
return false;
}
}
return true;
}
追加:新解决方案
正如我们提到的,您应该使用数组存储所有餐食,也可以使用Set存储部分,因为在Set中搜索比Array快。
const meals = [
{ activado: "on", porcion: "4" },
{ activado: "on", porcion: "1/8" },
{ activado: "on", porcion: "3" },
{ activado: "on", porcion: "1/2" },
];
function hasPortion(meals) {
const portions = new Set(["4", "3", "2", "1", "1/8", "1/4", "1/2"]);
return !meals.some((meal) => meal.activado === "on" && !portions.has(meal.porcion));
}
// Good case
console.log(hasPortion(meals)); // Output: true
// Add bad item
meals.push({ activado: "on", porcion: "1/3" })
console.log(hasPortion(meals)); // Output: false