function compare(a, b) {
return isNaN(a) || isNaN(b) ? a > b : +a > +b;
}
var c = compare(10,5);
alert("C value ==?"+c);
我无法理解上面的脚本。如何从 compare() 返回 bool 值 true
或 false
。生成的 bool 值true
是如何构成的。请解释。
最佳答案
return isNaN(a) || isNaN(b) ? a > b : +a > +b;
这会检查 a
或 b
是否不是数字 (IsNan
)。如果任一测试为真,则返回 a > b
的结果;如果它们都不是 NAN,则返回 +a > +b
的结果。阅读 Javascript 的文档 ternary (条件)运算符。
为了确保清楚,测试是:
if a is not a number or b is not a number, return true if a is greater than b, otherwise try to convert a and b both to numbers and return whether a is greater than b
请注意,整个表达式没有意义,因为即使在尝试转换之后,它也想返回可能不是数字的相等性测试。
关于javascript - bool 值如何从此语句返回 true 或 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6052802/