[英]Javascript Large amount of conditions
I am building a quiz to determine what kind of skin you have based off 3 questions (oily, dry.. etc)我正在做一个测验,根据 3 个问题(油性、干性等)来确定您的皮肤类型
Is the best way to write the logic for this, something like the below or is there a more efficient way of doing this in terms of performance是为此编写逻辑的最佳方法,如下所示,还是在性能方面有更有效的方法
if (q1 == 1 && q2 == 1 && q3 == 1){ skinType = "DRY" } else
if (q1 == 1 && q2 == 1 && q3 == 2){ skinType = "DRY" } else
if (q1 == 1 && q2 == 1 && q3 == 3){ skinType = "DRY" } else
if (q1 == 1 && q2 == 1 && q3 == 4){ skinType = "DRY" } else
if (q1 == 1 && q2 == 2 && q3 == 1){ skinType = "DRY" } else
if (q1 == 1 && q2 == 2 && q3 == 2){ skinType = "DRY" } else
if (q1 == 1 && q2 == 2 && q3 == 3){ skinType = "DRY" } else
if (q1 == 1 && q2 == 3 && q3 == 1){ skinType = "DRY" } else
if (q1 == 1 && q2 == 3 && q3 == 2){ skinType = "DRY" } else
if (q1 == 1 && q2 == 4 && q3 == 1){ skinType = "DRY" } else
if (q1 == 1 && q2 == 4 && q3 == 2){ skinType = "DRY" } else
if (q1 == 1 && q2 == 2 && q3 == 4){ skinType = "COMBO" } else
if (q1 == 1 && q2 == 3 && q3 == 3){ skinType = "COMBO" } else
....etc
在性能方面,没有什么比简单条件更快的了,但在可读性和代码维护方面则不然,这在编码中也很重要。
It depends on your data.这取决于您的数据。 Try to find patterns or input combinations that determine exactly the target class (eg q1 ==1 && q2 == 1 is always "DRY") and eleminate the redundant lines.
尝试找到准确确定目标类的模式或输入组合(例如 q1 ==1 && q2 == 1 总是“DRY”)并消除冗余行。
Since many of your input combinations seem to result in the same class, ie, DRY, COMBO, you could also try to build nested conditions similar to a decision tree .由于您的许多输入组合似乎产生相同的类,即 DRY、COMBO,您还可以尝试构建类似于决策树的嵌套条件。
if (q1 == 1) {
if (q2 == 1) {
skinType = "DRY";
} else if (q2 == 2) {
if (q3 == 4) {
skinType = "COMBO";
} else {
skinType = "DRY";
}
}
//...
}
One more sophisticated option to build good decision trees is the ID3 algorithm .构建良好决策树的一种更复杂的选择是ID3 算法。
您可以使用 Switch case 语句以获得更好的性能(“与 if-else 相比,switch 语句在大多数情况下更快”)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.