js,如果数组中的任何值小于或大于值 [英] js if any value in array is under or over value

查看:848
本文介绍了js,如果数组中的任何值小于或大于值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设您在一个数组中有(任意数量)个值,并且想查看它们中的任何一个是否超过(较低数量)且低于较高数量,那么您将如何做呢?

say you have (any amount) values in an array and you want to see if any of them is over (lower amount) and under higher amount, how would you do that?

无需执行for循环或任何冗长的代码即可得到答案.

answer without doing a for loop or any lengthy code.

也许是这样的:

var havingParty = false;
if ((theArrayWithValuesIn > 10) && (theArrayWithValuesIn < 100)) {
    havingParty = true;
} else {
    havingParty = false;
}

会工作的.

请注意:xy,碰撞检测,紧凑代码.

Please note: x and y, collision detection, compact code.

推荐答案

如果我正确理解了您的问题,则需要检查给定数组的值是否大于其他值.

If I understand your question correctly, you want to check if a given array has any value greater than some other value.

对此有一个有用的功能,称为some(

There is a useful function for this called some (Documentation here)

使用此示例:

const a = [1, 2, 3, 4, 5];
a.some(el => el > 5) // false, since no element is greater than 5
a.some(el => el > 4) // true, since 5 is greater than 4
a.some(el => el > 3) // true, since 4 and 5 are greater than 3

与此类似的功能是every,该功能检查所有值是否都满足给定条件(

A similar function to this is every, which checks if all the values fulfil a given condition (Documentation here).

例如:

const a = [1, 2, 3, 4, 5];
a.every(el => el > 3) // false
a.every(el => el > 0) // true

我的示例只是检查是否大于,但是您可以传递任何返回布尔值的回调,以进行更复杂的检查.

My examples simply check for greater than, but you could pass in any callback that returns a boolean value for more complicated checks.

因此,在您的示例中,如果要检查所有元素是否满足要求,则可以使用以下方法解决问题:

So for your example, something like this might do the trick if you want to check that all the elements fill the requirement:

const havingParty = theArrayWithValuesIn.every(el => el < 100 && el > 10);

const havingParty = theArrayWithValuesIn.some(el => el < 100 && el > 10);

如果您只关心至少一个元素满足要求.

if you you only care that at least one element fills the requirement.

这篇关于js,如果数组中的任何值小于或大于值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆