Type conversions
JavaScript is a weakly typed language, so the coercion type conversion is applied whenever possible.
The following comparison results are: true
New Number (10) = = 10; The string returned by Number.tostring () is converted to a number again
10 = = ' 10 '; String is converted to a number
10 = = ' +10 '; Ditto
10 = = ' 010 '; Ditto
isNaN (NULL) = = FALSE; Null is converted to number 0
0 Of course not a NaN (translator note: negation of denial)
The following comparison results are: false
10 = 010;
10 = = '-10 ';
ES5 Tip: Numeric literals that begin with 0 are parsed as octal digits.
In the ECMAScript 5 strict mode, this feature is removed.
To avoid the above complex coercion type conversions, it is strongly recommended to use a strict equals operator.
While this avoids most problems, JavaScript's weak-type system can still cause some other problems.
constructors for built-in types
The constructors of built-in types, such as number and String, are completely different when invoked, using or not using new.
New Number (10) = = 10; False, Comparison of objects with numbers
Number (10) = = 10; True, a comparison between numbers and numbers
New Number (10) + 0 = 10; True, because of implicit type conversions
Using the built-in type number as the constructor will create a new number object.
The number function, which does not use the New keyword, is more like a digital converter.
In addition, the introduction of literal values of objects in the comparison will result in more complex coercion of type conversions.
The best option is to explicitly convert the value to be compared to one of the three possible types.
Convert to String
' + 10 = = ' 10 '; True
Adding a value with an empty string can easily be converted to a string type.
Convert to Number
+ ' 10 ' = = 10; True
Using the unary plus operator, you can convert a string to a number.
A common way to convert strings to numbers:
+ ' 010 ' = = 10
Number (' 010 ') = = 10
parseint (' 010 ', 10) = = 10//used to convert to integer
+ ' 010.2 ' = = 10.2
Number (' 010.2 ') = = 10.2
parseint (' 010.2 ', 10) = = 10
Convert to Boolean
You can convert a value to a Boolean by using the No operator two times.
!!' Foo '; True
!!''; False
!!' 0 '; True
!!' 1 '; True
!!' -1 '//True
!! {}; True
!! True True