简体   繁体   English

用于在范围之间循环if的Javascript

[英]Javascript for looping an if between range

var data = [
   {
     color: "black"
     width: 0
    },
   {
     color: "black"
     width: 50
    },
   {
     color: "black"
     width: 100
    },
]

Case: 案件:

The function accepts an input which is a number. 该函数接受一个数字输入。 This number needs to be compared which data point it is within. 需要将此数字与其所在的数据点进行比较。

Conditions: 条件:

We know how much it will increase everytime. 我们知道每次都会增加多少。 In this case it is 50. 在这种情况下它是50。

We do not know how MANY objects there are. 我们不知道有多少对象。 In this case there are 3. 在这种情况下有3个。

It always starts at 0. 它始终从0开始。

This is a static function that could accomplish it (input = 55): 这是一个可以完成它的静态函数(输入= 55):

loopThis(input){
    if(input < 50){
        for(var i in data){
         data[i].color = "black";
        }
        data[0].color = "red";
    }else if(input > 50 && input < 100){
        for(var i in data){
         data[i].color = "black";
        }
        data[1].color = "red";
    }else{
        for(var i in data){
         data[i].color = "black";
        }
        data[2].color = "red";
    }
}

This would cause the second data object (data[1]) to become red and the rest will be black. 这将导致第二个数据对象(数据[1])变为红色,其余数据将变为黑色。

How take the conditions above and how can I make this code dynamic? 如何处理上述条件以及如何使此代码动态化?

This wouldn't work if we had 4 objects in the array. 如果我们在数组中有4个对象,这将不起作用。 And we can't know how many if conditions to write every time. 而且我们无法知道每次写入的条件有多少。

Try this code. 试试这个代码。

function loopThis(input){
    for(var i in data){
        data[i].color = "black";
    }
    var tmp = Math.floor(input/50);
    data[tmp].color = "red";
}

The tmp variable will give you the index to be marked red (for example if input is 51, tmp = 1; input 160, tmp = 3). tmp变量将为您提供标记为红色的索引(例如,如果输入为51,则tmp = 1;输入160,tmp = 3)。 That should solve the problem I guess. 这应该可以解决我猜的问题。

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

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