在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)
如何创建一个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)
| 归档时间: |
|
| 查看次数: |
740 次 |
| 最近记录: |