多个'如果'语句? [英] Multiple 'If' statements?

查看:118
本文介绍了多个'如果'语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个功能 checkTime ,如下所示,我必须同时检查多个条件。

Assume i have a function checkTime like the one below where i have to check for multiple condition simultaneously.

var result=0;
function checkTime(time1, time2) {

    if (time1 >= 0 && time2 <= 0) {
        result = 1;
    }
    else if (time1 >= 0 && time2 <= 1) {
        result = 4;
    }
    else if (time1 >= 2 && time2 <= 3) {
        result = 5;
    }
    else if (time1 >= 4 && time2 <= 6) {
        result = 6;
    }
    else if (time1 >= 7 && time2 <= 9) {
        result = 7;
    }
    else if (time1 >= 11 && time2 <= 12) {
        result = 8;
    }
    else if (time1 >= 13 && time2 <= 15) {
        result = 9;
    }
    else if (time1 >= 16 && time2 <= 17) {
        result = 10;
    }
    else if (time1 >= 19 && time2 <= 20) {
        result = 11;
    }
    return result;
}

(上面给出的例子是假设的)

(The above given example is hypothetical)

我使用的功能完全有效,但是:

The function i have used totally works,but:


  • 是否有更好的方法或程序或公式可供更换<?li>
  • Is there a better method or procedure or formula to replace this?(where it doesnt have to be this lengthy or ugly)

Thanx!

推荐答案

您可以使用数组来表示所有组合:

You can use an array to represent all the combination:

tests = [
    { time1: 0, time2: 0, result: 1 },
    { time1: 0: time2: 1, result: 4 },
    ...
];

for (var i = 0; i < tests.length; i++) {
    if (time1 >= tests[i].time1 && time2 <= tests[i].time2) {
        return tests[i].result;
    }
}

这篇关于多个'如果'语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆