在Javascript中进行严格(非类型转换)<,>,<=,> =比较的最佳和/或最短路径

kan*_*aka 27 javascript

在Javascript中,==比较具有严格(非类型转换)版本:===.同样,!=有严格的形式!==.这些保护您免受以下疯狂:

var s1 = "1",
    i1 = 1,
    i2 = 2;

(s1 == i1)   // true, type conversion
(s1 != i1)   // false, type conversion

(s1 === i1)  // false, no type conversion
(s1 !== i1)  // true, no type conversion
Run Code Online (Sandbox Code Playgroud)

但是,其他比较运算符没有等效的严格模式:

(s1 < i2)   // true, type conversion
(s1 <= i2)  // true, type conversion
([] < i2)   // true, wait ... wat!?
Run Code Online (Sandbox Code Playgroud)

显而易见的解决方案看起来非常冗长:

((typeof s1 === typeof i2) && (s1 < i2))  // false
Run Code Online (Sandbox Code Playgroud)

在Javascript中有更惯用(或更简洁)的方法吗?

参考:MDN 比较运算符

bfa*_*tto 11

没有内置的运算符可以满足您的需求,但您始终可以创建自己的函数.例如,对于<:

function lt(o1, o2) {
    return ((typeof o1 === typeof o2) && (o1 < o2));
}
lt("10", 11); // false
Run Code Online (Sandbox Code Playgroud)

如果您只处理字符串和数字,另一个选择是扩展String.prototype并且Number.prototype:

function lt(o) {
    return ((typeof this.valueOf() === typeof o) && (this < o));
}
String.prototype.lt = lt;
Number.prototype.lt = lt;
"10".lt(11);   // false
(11).lt("12"); // false
Run Code Online (Sandbox Code Playgroud)

  • @mjaything 我猜你来自一种具有严格类型或运算符重载或两者兼而有之的语言。JS 两者都没有,因此解决方案最终变得很麻烦。处理这个问题的 JS 方法是[类型强制算法](https://www.ecma-international.org/ecma-262/11.0/index.html#sec-abstract-relational-comparison)。 (2认同)

Sus*_* -- 7

如何创建一个Object并使用它

var strictComparison = {
    "<" : function(a,b) { return ((typeof a === typeof b) && (a < b)) },
    "<=" : function(a,b) { return ((typeof a === typeof b) && (a <= b)) },
    ">" : function(a,b) { return ((typeof a === typeof b) && (a > b)) },
    ">=" : function(a,b) { return ((typeof a === typeof b) && (a >= b)) }
};

console.log(strictComparison["<"](5,"6")) ;  
console.log(strictComparison[">"](5,6)) ;   
Run Code Online (Sandbox Code Playgroud)