javascript - Is there a way I can make this into a function or anything more efficient
问题描述
if (one >= 16 && one <= 20){
if (two >= 10){
Sum.innerHTML = "$2750";
} else {
Sum.innerHTML = "$2500";
}
} else if (one >= 20 && one <= 25){
if (two >= 10){
Sum.innerHTML = "$2500";
} else {
Sum.innerHTML = "$2250";
}
}
This is just a little of my code, its just a simple money calculator for something I'm doing with a friend, which doesn't really matter. I can't seem to think if there is any way I can make this more efficient by using a function of such because it just seems so much of the same code and is "dry" this is not all the code from it, there is so much of this... Don't know if anyone can help FYI this is in js and Sum is a paragraph id so just think of it as console log.
Thanks, Ethan
EDIT
https://codepen.io/anon/pen/bxgYWL?editors=10100 If you go onto that you can see all the code with all the commenting I could think to add to try and help you understand. Don't worry if it doesn't help and if there is no other way to make it efficient. It doesn't REALLY matter because it's just a private bit of code and shouldn't cause many problems.
解决方案
您可以使用数据结构来保存范围边界,然后对其进行循环。
var params = [
{ onelow: 16, onehigh: 20,
two: [ { low: -inf, high: 9, value: 2500 },
{ low: 10, high: +inf, value: 2750 }],
},
{ onelow: 21, onehigh: 25,
two: [ { low: -inf, high: 9, value: 2250 },
{ low: 10, high: +inf, value: 2500 }],
},
...
];
let done = false;
for(let i = 0; !done && i < params.length; i++) {
let param = params[i];
if (one >= param.onelow && one <= param.onehigh) {
let done = false;
for (let j = 0; j < param.two.length; j++) {
let param2 = param[j];
if (two >= param2.low && two <= param2.high) {
Sum.innerHTML = "$" + param2.value;
done = true; // stop the outer loop, too
break;
}
}
}
}
推荐阅读
- python - 为什么我的 google colab 会话不断崩溃?
- angularjs - 如何在 AngularJS 的模态实例控制器上访问控制器方法?
- c# - 确保调用api成功并保存自己成功
- php - 使用 netbeans IDE 调试 PHP 应用程序
- r - 混合模型中的计划对比
- python - 无法在 Django 模板中获取字典值
- python - 将 dict 的 pandas 数据框列展开为数据框列
- javascript - 如何将 JavaScript 数据放入 Gmail 识别为 URL 的 URL?
- spring - 将 Spring Integration 与 Spring MVC 结合使用时出现部署错误
- vert.x - Vertx:使用 AbstractVerticle Context 传递对象