JavaScript is typically divided into two types of conversions, implicitly coercion type conversions (implicit coercion) and explicit coercion of type conversions (explicit coercion).
The source code of all the following codes can be viewed here .
One, cast to string (ToString)
1) ToString
The string rule for the base type value is: null is converted to "null", undefined is converted to "undefined", and true is converted to "true". The string of numbers follows the general rules, but those very small and large numbers use the exponential form:
// 1.07 consecutive times seven x var a = 1.07 * * * * * * * * // Seven 10,001 a total of 21 digits // "1.07e21"
For normal objects, toString () (Object.prototype.toString ()) Returns the value of the internal property [[Class]] unless it is defined by itself
2) JSON
Json.stringify (..) When you encounter undefined, function, and symbol in an object, it is automatically ignored, and null is returned in the array (to ensure that the cell position is unchanged).
If the Tojson () method is defined in the object, the JSON string is called first and then serialized with its return value.
// undefined Json.stringify (function// undefinedjson.stringify ( [function()] {}, 4// "[1,null,null,4]"json.stringify ({ 2, function// "{" A ": 2}"
Ii. forced conversion of numbers (Tonumber)
1) Tonumber
1. true converts to 1,false to 0;
2. undefined converted to NaN,null converted to 0;
3. "",[] convert to 0. A NaNis returned when processing fails.
4. Tonumber the hexadecimal number starting with 0 is not processed in hexadecimal .
2) Object
Objects (including arrays) are first converted to the corresponding base type values , and if they are returned as a non-numeric base type value, they are then coerced to a number by following the rules above .
To convert a value to the corresponding base type value, the abstract operation Toprimitive first checks whether the value has a valueof () method (through an internal operation DefaultValue).
If it has and returns a base type value, the value is used to force the type conversion. If no, the return value of ToString () is used (if present) to force the type conversion.
varA ={valueOf:function() {//Execute valueof First return"42"; }};varb ={toString:function() {//then execute ToString return"42"; }};varc = [4, 2];c.tostring=function() { return This. Join ("");//" A"}; Number (a); // theNumber (b);// theNumber (c);// theNumber ("");//0Number ([]);//0Number (["ABC"]);//NaN
Three, cast Boolean (ToBoolean)
1) False value (Falsy value)
You can force the type to be converted to false. Includes undefined,null,false,+0,-0,NaN, "".
Undefined,null,false, +0,-0, NaN, ""
2) Truth
[],{} , and function () {} are not in the list of false values.
[], {}, and function () {}
Iv. explicit coercion of type conversions
1) Strange ~ operator
~x is roughly equivalent to -(x+1).
~42; // -(42+1) ==> -43
Use ~ ~ to intercept the numeric value of the decimal part ~ ~ The first ~ to execute ToInt32 and reverse the word bit, and then the second ~ and then a bit reversal, all the words will be reversed back to the original value, the final result is still ToInt32.
// a Strange ~ var a = "Hello world"; if // // }//~// -50// -49
2) Explicit parsing of numeric strings
parsing allows strings to contain non-numeric characters, parsing in left-to-right order, and stopping if non-numeric characters are encountered.
The conversion does not allow non-numeric characters, otherwise it fails and returns Nan.
var a = "a"; var b = "42px"// ///// NaN // the
The parsefloat (..) function can be used to resolve floating-point numbers in a string.
A non-string parameter is first coerced into a string (executing the tostring method).
// 0 ("0" from "0.000008") // parseint (false/ /// ("F" from "function ...") parseint ( //// 2
V. Implicit coercion type
1) implicit coercion of type conversions between strings and numbers
If + one of the operands is a string, the string concatenation is performed, otherwise the numeric addition is performed.
If one of the operands is an object (including an array), the Toprimitive abstract operation is invoked on it.
var a = "a"; var b = "0"// "420" two are all string var c = Zero; var d = 0// 422 are all numeric var a = [1, 2]; var b = [3, 4// "1,23,4" two are objects
2) implicit coercion type conversion to Boolean value
In the following cases, non-Boolean values are implicitly coerced to a Boolean value, followed by the ToBoolean abstract operation rule.
1. If (..) The conditional judgment expression in the statement.
2. For (..;..;..) The conditional judgment expression in a statement (the second).
3. While (..) and do . While (..) The conditional judgment expression in the loop.
4. : The conditional-judging expression in.
5. Logical Operators | | (logical OR) and &&(logical AND) the operand to the left (as a condition-determining expression).
Six, loose equal and strictly equal
The common misconception is "= = Check if values are equal, = = = Check values and types are equal". It sounds reasonable, but it's not accurate enough.
The correct explanation is: " = = allows coercion of type conversions in equality comparisons, and = = = does not allow "
1) Equality comparison between a string and a number
1. If type (x) is a number, type (y) is a string, then the result of x = = Tonumber (y) is returned.
2. If type (x) is a string, type (y) is a number, the result of tonumber (x) = = y is returned.
2) Equality comparison between other types and Boolean types
1. If type (x) is a Boolean type, returns the result of Tonumber (x) = = Y.
2. If type (y) is a Boolean type, returns the result of x = = Tonumber (y).
3) Equality comparison between null and undefined
1. If x is null and y is undefined, the result is true.
2. If x is undefined and y is null, the result is true.
4) Equality comparison between objects and non-objects
1. If type (x) is a string or number, type (y) is the object, the result of x = = Toprimitive (y) is returned.
2. If type (x) is an object, type (y) is a string or number, the result of topromitive (x) = = y is returned.
varA = "abc";varb = Object (a);//As with new String (a)A = = = B;//false//b enforces type conversions through Topromitive (also known as "unpacking", unboxed or unwrapped), and returns the scalar base type value "ABC", which is equal to a. A = = B;//true//null and undefined cannot be encapsulated (boxed), object (null), and object (undefined) return a regular object. varA =NULL;varb = Object (a);//as with object ()A = = B;//falsevarc =undefined;varD = Object (c);//as with object ()c = = D;//false//Nan can be encapsulated as a digital wrapper object, but Nan is not equal to NanvarE =NaN;varF = Object (e);//As with new number (e)E = = f;//false
5) Equal comparison of false values
The false value is the false value mentioned above in the ToBoolean.
"0" = = false ; // true according to 2) and 1) false = = 0; // true in accordance with rule 2) false = = ""; // true according to 2) and 1) false = = []; // true according to 4) 2) 1) The rule "" = = 0; // true according to 1) "" = = []; // true in accordance with rule 4) 0 = = []; // true according to 4) 1) Rules [] == ! []// true![] The value after execution is false
6) Safe use of implicit coercion type conversions
1. Do not use = = if the values in both sides have true or false.
2. If there are [], 0, or "" in the values on both sides, try not to use = =.
7) Comparison Chart
An online chart provided by Dorey.
JavaScript you don't know Collation (vi)--Forced type conversion