首页 > 解决方案 > 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.

标签: javascript

解决方案


您可以使用数据结构来保存范围边界,然后对其进行循环。

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;
            }
        }
    }
}

推荐阅读