给定 2 个正 int 值,返回 10.20 范围内(含 10.20)的较大值,如果两者都不在该范围内,则返回 0

Given 2 positive int values, return the larger value that is in the range 10..20 inclusive, or return 0 if neither is in that range

本文关键字:范围内 返回 两者都 如果 int 个正 给定      更新时间:2023-09-26

我的问题是我似乎无法访问第二个else/if语句,在该语句中,我尝试包含一个子句,如果一个数字仍在范围内,它仍然应该返回。语法都是正确的,我被告知我的括号放置不正确,但我无法理解在哪里或如何。

var max1020=function(a, b) {
    if ((a >= 10 && a <= 20) && (b >= 10 && b <= 20)) { 
        if (a > b) { //comparing my a and my b and returning greater
            return a;  
        } else if (b > a) {
            return b;
        } else if ((a >= 10 && a <= 20) || (b >= 10 && b <= 20)) { 
            if (a >= 10 && a <=20) {
                return a;
            } else if (b >= 10 && b <=20) {
                return b;
            }
        } else {
            return 0;
        }
    }
};
您可以使用

Math.max进行适当的检查,并在范围内进行适当的检查。

function range(a, b) {
    function inRange(v) {
        return v >= 10 && v <= 20 ? v : 0;
    }
    return Math.max(inRange(a), inRange(b));
}
console.log(range(-1,-5));
console.log(range(1, 5));
console.log(range(10, 5));
console.log(range(10, 15));
console.log(range(100, 15));

如果 a

大于 b 并且 b 大于 a,您似乎正在返回。所以你唯一会到达第二个的时候是当 a = b 时?也许我错过了什么。

var max1020=function(a, b) {
 var max = (a>b?a:b);   //first find the max value of a and b 
 if(max>=10&&max<=20) return max; //if max is in range then at 
                                 //least on of them is in range and is bigger
 else if(a>=10 && a<=20) return a; //if the max in not in range then only one could be in range so return the one that in range
 else  if(b>=10 && b<=20) return b;
 return 0;  //if you reach this point none of them was in range
};

如果您利用一些新的 ES6 功能,则可以使您的函数更短、更简单、更好。

function maxRange(min, max, ...values) {
  values = values.filter(e => e >= min && e <= max);
  return values.length ? Math.max(...values) : 0;
}

您可以指定范围,并且不限于 2 个值。你可以这样使用它

maxRange(10, 20, 10, 15)  // Returns 15
maxRange(10, 20, 10, 15, 20, 30)  // Returns 20
maxRange(10, 20, 5, 25, 99)  // Returns 0
maxRange(100, 150, 99, 120, 200)  // Returns 120
maxRange(-50, -20, 12, -77, 123, -24) // Returns -24

这是一个更长的版本,带有注释,以更好地了解它是如何工作的。

function maxRange(min, max, ...values) {    // Collects the remaining arguments in an array with the rest operator
  values = values.filter(e => {     // Filter the arguments. Using the arrow function
    if(e >= min && e <= max) {      // Test if an argument is in range
      return true;      // Keep it if its in range
    }
    else {
      return false;     // Discard it otherwise
    }
  });
  if(values.length) {   // Test if we have any arguments left
    return Math.max(...values); // Return the highest of them. Using the spread operator
  }
  else {
    return 0;       // Return 0 if no argument was in range
  }
}

以下是有关我使用过的功能的更多信息

休息运算符

点差运算符

箭头功能

阵列过滤器

条件(三元)运算符