当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Check all variables in an array for an if condition

问题描述:

Lets say I have variables which are "a, b, c, d, e, f" and I want to check if any of them have a value bigger than 10.

 var myvars = [a,b,c,d,e,f]

if((Any value in these variables) > 10) {

//do something

}

I searched but I can't find a shorter way than checking them one by one. Any ideas will make me happy.

网友答案:
var numbers = [1, 5, 7, 3, 9];
var max = Math.max.apply(Math, numbers);

if(max > 10) {
    // contains a number that is greater than 10
}

or short form:

var numbers = [1, 5, 7, 3, 9];
if(Math.max.apply(Math, numbers) > 10) {
    // contains a number that is greater than 10
}
网友答案:

Use the some method of arrays

if (myvars.some(function(x) {
    return x > 10;
})) {
    // do something
}
网友答案:

You can use filter method on array.

function customFilter(e) {
  return e > 10;
}
var filtered = [12, 5, 8, 130, 44].filter(customFilter);
网友答案:

I use underscore some for this kind of traversing/manipulation

var myvars = [a,b,c,d,e,f];
if(_.some(myvars,function(element) { return element>10; })) {
    //something
}

it delegates on array some when available (but still works if it isn't). You can also use it on objects.

网友答案:

Try this code:

void Main()
{
    int a = 1;
    int b = 2;
    int y = 23;
    int z = 24;
    List<int> letterAsNumber = new List<int>{a,b,y,z};

    var over10 = letterAsNumber.Where( r => r > 10 );  //here
    foreach( int o in over10 )
        Console.WriteLine(o);
}

If you're using visual studio and you hit the dot you can see more options like .ToList().

分享给朋友:
您可能感兴趣的文章:
随机阅读: