简体   繁体   English

检查数组中的所有变量是否为if条件

[英]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. 可以说我有“ a,b,c,d,e,f”变量,我想检查其中是否有一个大于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 使用数组的some方法

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(). 如果您使用的是Visual Studio,但碰到了点,您会看到更多选项,例如.ToList()。

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

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