[英]Best and/or shortest way to do strict (non-type converting) <, >, <=, >= comparison in Javascript
In Javascript, the ==
comparison has a strict (non-type converting) version: ===
. 在Javascript中, ==
comparison具有严格(非类型转换)版本: ===
。 Likewise, !=
has the strict form !==
. 同样, !=
有严格的形式!==
。 These protect you from the following craziness: 这些保护您免受以下疯狂:
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
However, the other comparison operators have no equivalent strict modes: 但是,其他比较运算符没有等效的严格模式:
(s1 < i2) // true, type conversion
(s1 <= i2) // true, type conversion
([] < i2) // true, wait ... wat!?
The obvious solution seems pretty verbose: 显而易见的解决方案看起来非常冗长:
((typeof s1 === typeof i2) && (s1 < i2)) // false
Is there a more idiomatic (or just less verbose) way to do this in Javascript? 在Javascript中有更惯用(或更简洁)的方法吗?
Reference: MDN Comparison Operators 参考:MDN 比较运算符
There are no built-in operators for what you want, but you can always create your own functions. 没有内置的运算符可以满足您的需求,但您始终可以创建自己的函数。 For example, for <
: 例如,对于<
:
function lt(o1, o2) {
return ((typeof o1 === typeof o2) && (o1 < o2));
}
lt("10", 11); // false
Another option, if you're only dealing with strings and numbers, is extending String.prototype
and Number.prototype
: 另一个选择,如果你只处理字符串和数字,则扩展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
How about creating a Object and using it 如何创建一个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)) ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.