简体   繁体   English

为更多 ajax 项目制作 if (test >= 0 && test <=3) 的更简单方法

[英]Easier way to make if (test >= 0 && test <=3) for more ajax items

there is easier way to catch 4 items (variable test) and give 4 elements (variable i), if I continue with if () it works as I want but it will result in a lot of if ().有更简单的方法来捕获 4 个项目(变量测试)并给出 4 个元素(变量 i),如果我继续使用 if(),它可以按我的意愿工作,但会导致很多 if()。

if(test >= 0 && test <=3) {
    if(i >= 0 && i <=3) {
        $(sample).appendTo($example);
    }
}

if(test >= 4 && test <=7) {
    if(i >= 4 && i <=7) {
        $(sample).appendTo($example);
    }
}

Example:
0  1  2  3 (variable i: 0 1 2 3)
4  5  6  7 (variable i: 4 5 6 7)
8  9  10 11 (variable i: 8 9 10 11)
12 13 14 15 (variable i: 12 13 14 15)

You seem to need this simple check:你似乎需要这个简单的检查:

    if (Math.floor(test/4) === Math.floor(i/4))

You can divide both the numbers by 4 to see if they have the same quotient .您可以将这两个数字除以 4 以查看它们是否具有相同的quotient This will give you the behavior you desire (as suggested in OP).这将为您提供您想要的行为(如 OP 中所建议的)。

See code snippet below:请参阅下面的代码片段:

 var inSameBlock = (test, i) => Math.floor(test/4) === Math.floor(i/4); console.log(inSameBlock(1, 2)); console.log(inSameBlock(1, 5)); console.log(inSameBlock(5, 5)); console.log(inSameBlock(5, 7));

Use Array.prototype.every .使用Array.prototype.every Using this approach, you just need to update the vals array if you want more values to be checked.使用这种方法,如果要检查更多值,只需更新vals数组。

var vals = [test,i]

if (vals.every(v => v >= 0 && v <= 3)) {
   $(sample).appendTo($example);
}
if (vals.every(v => v >= 4 && v <= 7)) {
   $(sample).appendTo($example);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM