Home > Article > Web Front-end > What types of conversions does JavaScript have?
JavaScript type conversions include: 1. To convert to a string, use ".toString", String or "num """; 2. To convert to a numeric type, use Number, parseInt or parseFloat; 3. To convert to a Boolean value, use Boolean or "!!".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
1. Convert to string: Use .toString or String.
1, .toString() method: Note that null and underfined cannot be converted
//转为字符串-->toString方法 var bool=true; console.log(bool.toString()); //注意,toString不能转null和underfined.
2, String() method: both can Conversion
console.log(String(null));
3. Implicit conversion: num "", when one operator on both sides is a string type and one operator is another type, the other type will be converted into a string first and then the string Splice, return string
var a=true; var str= a+""; console.log('str');
2. Convert to numerical type
1, Number(): Number() can convert any value into a numerical value. If there is a character that is not a numerical value in the string to be converted, NaN
console.log(Number(true));
2, parseInt():
var a="12.3px"; console.log(parseInt(a); //结果:12.3. 如果第一个字符是数字会解析知道遇到非数字结束. var a="abc2.3"; console.log(parseInt(a); 结果:返回NaN,如果第一个字符不是数字或者符号就返回NaN.
3, is returned. parseFloat(): parseFloat() converts a string into a floating point number, parseFloat() is very similar to parseInt, the difference is that parseFloat will parse the first one. The second one is encountered. Or end with non-number. If the parsed content contains only integers, parse it into integers.
4. Implicit conversion:
var str="123"; var num=str-0; console.log(num); //结果为数值型;
3. Conversion to Boolean(): 0 '' (empty string) null undefined NaN will be converted to false and others will be converted to true
Method:
1, Boolean():
console.log(Boolean(2));
2,
var message; if(message){};
3, Implicit conversion: ! !
var str="123"; var bool=!!str; console.log(str);
【Recommended learning: javascript advanced tutorial】
The above is the detailed content of What types of conversions does JavaScript have?. For more information, please follow other related articles on the PHP Chinese website!