javascript中由于是弱类型,所以在比较的时候有较大的麻烦。这次专门做了总结:
Comparison operators are used in logical statements to determine equality or difference between variables or values.
Given that x=5, the table below explains the comparison operators:
Operator |
Description |
Comparing |
Returns |
== |
equal to |
x == 8 |
false |
x == 5 |
true | ||
=== |
exactly equal to (equal value and equal type) |
x === "5" |
false |
x === 5 |
true | ||
!= |
not equal |
x != 8 |
true |
!== |
not equal (different value or different type) |
x !== "5" |
true |
x !== 5 |
false | ||
> |
greater than |
x > 8 |
false |
< |
less than |
x < 8 |
true |
>= |
greater than or equal to |
x >= 8 |
false |
<= |
less than or equal to |
x <= 8 |
true |
1. === vs ==
JavaScript has both strict and type-converting equality comparison. For strict equality the objects being compared must have the same type and:
2. > & <
Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.
‘00100‘<‘1‘// true
as they are both strings so only the first zero of ‘00100‘ is compared to ‘1‘ and because it‘s charCode is lower, it evaluates as lower.
However:
‘00100‘<1// false
as the RHS is a number, the LHS is converted to number before the comparision.
不过 最好在比较前 做类型转换: parseInt Number parseFloat。
原文地址:http://www.cnblogs.com/reynold-lei/p/3726901.html