如何正确进行比较

How to do comparison correctly

本文关键字:比较 何正确      更新时间:2023-09-26

我正在尝试检查最小值是否总是小于最大值和最小值,最大值始终是一个数字,最小值和最大值不为空。

我注意到它从不检查这一点,而是直接进入错误消息。我做错了什么?

var min=30
var max=5000;
if(isNaN(min)=="false" || isNaN(max)=="false") && (min!=""|| max!="") && (max > min))
{
 document.write(min+ max);
}else
{
 document.write("give error msg");
}
你应该

使用 JavaScript Number()来检查某些东西是否是数字。 无论如何,NaN评估为 false,因此您只需检查这是否满足您的所有要求,而不是某些要求。如果min不是数字,则失败,如果max不是数字,则失败,如果min小于max,则失败。这看起来像这样:

var min = 30
var max = 5000;
// You only need to check if its a Number using the default Number function which will
// return NaN if its not and convert if it can be converted.
if(Number(min) && Number(max) && (min <= max)){
    document.write(min + ", " + max);
} else {
    document.write("Min or Max is not a number or Min is bigger than Max");
}

现在,正如一些人指出的那样,这将有一些边缘情况,所以这里有一些可以解决它的方法:

function getNumber(n){
    // Take a number 'n' and return 0 if false if its not a number.
    return Number(n) === 0 ? 0 : Number(n) || false;
    // Broken down this means:
    // Check if n is the number 0. Yes? Return 0. No? Check if n is a number. Yes? Return that. No? Return false;
}
if(getNumber(min) !== false && getNumber(max) !== false && (min <= max)){
    document.write(min + ", " + max);
}

或者正如@IsmaelMigual评论中所说,通过除以 1 然后比较来简化它:

function isNumber(n){
    // Returns true or false
    return n / 1 == n / 1;
}
if(isNumber(min) && isNumber(max) && (min <= max)){
    document.write(min + ", " + max);
}

if(isNaN(min)=="false"将始终返回false,因为该函数将返回truefalse,但永远不会"false"(这是一个字符串)。
此外,您应该在第一个括号中使用"and"。
试试这个:
if(! isNaN(min) && ! isNaN(max)) && (...
编辑:试试这个条件:
if((! isNaN(min) && ! isNaN(max)) && max> min && min > 0 ) { (...