在switch语句中,是否可以在每种情况下都使用模运算符?



是否可以使用switch语句做这样的事情?

switch(foo) {
    case %bar==0:
    //Do stuff
    break;
}

为了更清楚,switch语句应该检查foo是否被某数整除为0/在每种情况下foo是否被某数整除

另一种选择是任何Array迭代器,其中bar定义为值数组。

function fooMod(foo){
    var A= [];
    [2, 3, 4, 5, 6, 7, 8, 9].forEach(function(itm){
        if(foo%itm=== 0){
            A.push(itm+' is a factor of '+foo);
        }
        else{
            A.push(itm+' is not a factor of '+foo);
        }
    });
    return A;
}

fooMod (24) . join(" n");

/*  returned value: (String)
2 is a factor of 24
3 is a factor of 24
4 is a factor of 24
5 is not a factor of 24
6 is a factor of 24
7 is not a factor of 24
8 is a factor of 24
9 is not a factor of 24
*/

开关将一个评估结果(如fn(foo), foo+bar, foo%bar)与各种可能的结果进行比较。您想要计算多个值[foo%bar1, foo%bar2,...]]并找到第一个等于0的值。

我看不出有什么方法可以用switch(你可以使用直通,但这是一种迂回的方法)

相关内容

最新更新