Method: 1. Use the " " operator to automatically convert. 2. Use JS’s built-in functions for conversion. For example, toString() and String() can be converted into strings, Number() and parseInt() can be converted into numeric types, and Boolear() can be converted into Boolean types.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 5, Dell G3 computer.
1. Convert to string
1. Use toString method:
This method Not suitable for null and undefined, they have no toString method
var num = 18; var isRight = true; var a = null; console.log(num.toString()); console.log(isRight.toString());
2. Use the String method:
This method is often used to convert null and undefined into string types
console.log(String(num)); console.log(String(isRight)); console.log(String(a));
3. Splicing
console.log(num+''); console.log(isRight+''); console.log(a+'');
2. Convert to numerical type
1 , Number method
Number method returns NaN as long as there is one letter in the string, and can convert boolean type
var str1 = '123'; var str = 'abc'; var str2 = '123abc' var isRight = true; console.log(Number(str1));//值为123 console.log(Number(str));//值为NaN(不是数值) console.log(Number(str2))//Number方法只要字符串中有一个字母则返回NaN console.log(Number(isRight));//值为1
2, parseInt method
The parseInt method converts a numeric value into a number in a string. If it encounters a non-number, it will return. The boolean type cannot be converted.
console.log(parseInt(str1));//值为123 console.log(parseInt(str));//值为NaN console.log(parseInt(str2));//parseInt方法在字符串中遇到数值转换成数字,如果遇到非数字就会返回
3, parseFloat method
Similar to parseInt, if there are only integers in the parsing, it will be parsed as integers
console.log(parseFloat(str1)); console.log(parseFloat(str)); console.log(parseFloat(str2)); console.log(parseFloat(isRight));//如果解析中只有整数则解析为整数
4, add ' ' or '-' method
Strings with letters cannot be converted, and boolean types can be converted:
"-" has a value and a string. First convert the string into a value, and then subtract. If the value conversion fails, it will be NaN
" "One side is a value and the other is a string, first convert the value into a string, and then concatenate it
console.log(+str1); console.log(-str1); console.log(+str2);//不能转换有字母的字符串 console.log(+isRight);//值为1 console.log(str1-0);//值为123
3. Convert to Boolear type
1. Use Boolear method:
Five cases of conversion to false: null undefined ''(empty string) 0 NaN
var str = 'abc'; var num = 123; var a = null; var b; console.log(Boolean(str)); console.log(Boolean(num)); console.log(Boolean(a)); console.log(Boolean(b));
More programming related For knowledge, please visit: programming video! !
The above is the detailed content of How to type convert in javascript. For more information, please follow other related articles on the PHP Chinese website!