Type change in javascript

Type conversion in javascript

JavaScript is a weakly typed language, variables and types have nothing to do, so sometimes we need to perform type conversion

1. Number conversion (number)

Two methods:

number: 类型转化走的是v8引擎最底层机制的转化规则
parseFloat、parseInt:是提供额外的方法转化规则

number

First convert the reference type to a string (tostring) method, and then convert the string to a number

字符串 => 数字:非有效数字转化为字符串
布尔值 => 数字 :1或0
null => 数字 : 0;
underfined => 数字 :NaN,
‘ ’ => 数字 :0
对象 => 数字:先把对象转化成为字符串,在转化成为数字
【】 => 数字 :0

Number(10); // 10 
Number('10'); // 10 
Number(null); // 0
Number(''); // 0
Number(true); // 1 
Number(false); // 0
Number([]); //
0 Number([1,2]); // NaN
Number('10a'); // NaN 
Number(undefined); // NaN

parseint() parsefloat([va],[base]), search the string from left to right for valid numeric characters, knowing that it encounters an invalid string, stop the search, and return the found as a number,

If it is not a string, first convert it to a string and use this method

let str = '12.5px' 
parseInt(str) // 12 
parseFloat(str)// 12.5
parseFloat(true)// NaN

isNaN determines the number type:

If the current type is a number type, return false, otherwise return true

2. String type conversion (string)

The primitive type, using the tostring method () is what it looked like before wrapping a layer of quotation marks

数字 => 字符串:包裹一层引号。
NaN => 字符串: 'NaN' 。 
true => 字符串: 'true' 。 
null => 字符串: 'null' (浏览器会报错(禁止你使用)—— 通常可以进行转换)
undefined => 字符串:'undefined' (浏览器会报错(禁止你使用)—— 通常可以进行转换)
Object => 字符串: '[object,Object]' 。

The result of ordinary object conversion is "[object,object]", because the Object.prototype.toString method is not converted to a string, but is used to detect the data type.

String(123); // "123" 
String(true); // "true" 
String(null); // "null"(报错) String(undefined);// "undefined"(报错) String([1,2,3]) // "1,2,3" 
String({}); // "[object Object]"

Three, Boolean type conversion (boolean)

1:‘ ’,

2:underfined,

3 : NaN

4:null,

5:false,

6: 0 ,

The above 6 values ​​are false when converted to boolean, and all other types are true

Boolean('') // false
Boolean(undefined) // false
Boolean(null) // false
Boolean(NaN) // false
Boolean(false) // false
Boolean(0) // false 
Boolean({}) // true
Boolean([]) // true

Fourth, the conversion of primitive types

There are two cases for converting primitive types: converting to string types or other primitive types .

If it is already a primitive type, no conversion is required.

If you convert to a string type, call the toString() method in the built-in function.

If it is other basic types, call the valueOf() method in the built-in function.

If the returned type is not primitive, the toString() method will continue to be called.

If the original type has not been returned, an error is reported.

Guess you like

Origin blog.csdn.net/weixin_44865458/article/details/114399781