Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”
In the daily development, the problem of type conversion has been accompanied by our code programming, whether framework, the writing of the library, or a business development, the type conversion operation is necessary, will from time to time, we need to take the initiative to conduct casts or implicit type conversion, so when the type conversion needs to keep an eye, So as not to leave difficult problems to investigate (personally experienced many times, each investigation is very painful 😂😂😂)
Cast casting
Mandatory type conversion methods: Number, parseInt, parseFloat, String, Boolean, etc
These methods are similar in that each casts a data type in its own way. Let’s look at the Number and Boolean casts
The cast rule for the Number method:
- If Boolean, true and false are converted to 1 and 0, respectively;
- If it is a number, return itself;
- If null, return 0;
- If undefined, NaN is returned;
- If it is a string, follow these rules: If the string contains only numbers (or a string of hexadecimal digits starting with 0X / 0X, plus or minus signs are allowed), convert it to decimal; If the string contains a valid floating-point format, convert it to a floating-point value; If it is an empty string, it is converted to 0; NaN is returned if it is not a string of the above format;
- If Symbol, an error is thrown;
- Call this method if it is an object and [symbol.toprimitive] is deployed, otherwise call the valueOf() method of the object and convert the returned value according to the previous rules; If the result of the transformation is NaN, the object’s toString() method is called, and the transformation returns the corresponding values again in the previous order
Next, analyze the output for yourself
Number(null); / / 0
Number(' '); / / 0
Number(true); / / 1
Number(false); / / 0
Copy the code
Boolean method cast rules:
False: undefined, null, false, ”, +0, -0, NaN
All but seven of the above conversions are true
Boolean(0); //false
Boolean(null); //false
Boolean(undefined); //false
Boolean(NaN); //false
Boolean(1); //true
Boolean(13); //true
Boolean('12'); //true
Copy the code
Casts are relatively simple and can be developed with pleasure after mastering a few common apis