Javascript:如何检查数组的数字是否在一个范围内 [英] Javascript: how to check if array's numbers is in a range

查看:157
本文介绍了Javascript:如何检查数组的数字是否在一个范围内的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有validRange(x,y,z)函数,它得到一个数组和2个数字,如果数组的数字位于这2个数字的范围内,那么它返回true,如果数组包含的数字不在范围内,该函数返回false。例如`validRange([11,1,15,13,​​14],10,20);这将返回false,因为1不在范围内,

validRange([11,15,13,​​14],10,20)这将返回true。



我尝试了什么:



我试过这样的,但为什么它不起作用?< br $>


函数validRange(x,y,z){
for(var i = 0; i< x.length; i ++ ){
if(x [i]> y&& x [i]< z){
return true;
}
else {
返回false;
}
}
}


console.log(validRange([11,1,15,13,​​14],10,20)) ; //在这种情况下它返回true,但它必须返回false

解决方案

您的代码只检查第一个数组值并立即返回。仅在条件不满足时立即返回并最终在循环外返回true:

 function validRange(x,y,z){
for var i = 0 ; i < x.length; i ++){
if (x [i] < y || x [i] > z){
// 值超出范围
return ;
}
}
// 所有值都在范围内
return true ;
}

另请注意,我已将条件更改为超出范围,使得与其中一个限制相同的值被视为有效(通常情况下,范围是包括限制)。如果情况不是这样,请将比较更改为< = > =


I have validRange(x,y,z) function, it gets an array and 2 numbers, If array's numbers located in this 2 number's range then it returns true, If the array contains a number that is not in the range, the function returns false. For example` validRange([11,1,15,13,14], 10, 20); this will return false, cause 1 is not in range,
validRange([11,15,13,14], 10, 20) and this will return true.

What I have tried:

I have tried like this, but why is it not working?

function validRange(x, y, z) {
	for(var i = 0; i < x.length; i++){
		if(x[i] > y && x[i] < z){
			return true;
		}
		else{
			return false;
		}
	}
}


console.log(validRange([11,1,15,13,14], 10, 20)); //in this case it returns true, but it must return false

解决方案

Your code checks only the first array value and returns immediately. Return immediately only if the condition is not met and return true finally outside the loop:

function validRange(x, y, z) {
    for(var i = 0; i < x.length; i++){
        if(x[i] < y || x[i] > z){
            // Value is outside the range
            return false;
        }
    }
    // All values are inside the range
    return true;
}

Note also that I have changed the condition to be outside the range in a way that values which are identical to one of the limits are treated as valid (it is common with ranges that the limits are included). If this should not be the case, change the to comparisons to <= and >=.


这篇关于Javascript:如何检查数组的数字是否在一个范围内的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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