JS中的数据类型
一、数据类型
基本数据类型(栈内存) | 引用数据类型(堆内存) |
---|
number | object(普通对象、数组对象、…) |
string | function |
boolean | |
null | |
undefined | |
symbol(ES6) | |
bigint(ES6) | |
二、数据类型检测
方法名 | 作用 | 使用案例 |
---|
typeof | 检测数据类型,返回类型名称 | typeof(2) --> number |
instanceof | 检测是否为某个类型的实例,返回 ture/false | [1, 2] instanceof Array --> true |
constructor | 检测构造函数,返回 ture/false,纯数字、null、undefined不可用 | [1,2].constructor == Array --> true |
Object.prototype.toString.call | 检测数据类型,返回[object,Type] | Object.prototype.toString.call(1) --> “[object Number]” |
三、数据类型转换
转换成Number类型:Number(“123”)、parseInt(“123”)、parseFloat(“123.44”)、isNaN(“123”)、…
表达式 | 值 |
---|
true | 1 |
false | 0 |
null | 0 |
undefined | NaN |
Number(“”) | 0 |
parseInt(“”) | NaN |
isNaN(“”) --> isNaN(0) | false |
parseInt(null) --> parseInt(“null”) | NaN |
Number(null) | 0 |
isNaN(null) --> isNaN(0) | false |
parseInt(“16px”) | 16 |
Number(“16px”) | NaN |
isNaN(“16px”) --> isNaN(NaN) | true |
parseFloat(“1.2px”) + parseInt(“2px”) + typeof parseInt(null) --> 1.2 + 2 + typeof NaN --> 2.2 + “number” | “2.2number” |
isNaN( Number( !!Number( parseInt(“0.2”) ) ) ) | false |
typeof !parseInt(null) + isNaN(null) | booleantrue |