《用得上的前端知识》系列 - 你我都很忙,能用100字说清楚,绝不写万字长文
数据类型
- 基本数据类型
-
- number
-
-
- NaN / Infinity
- 转换方法:
- 强转化:基于底层机制转换(一些隐式转换都是基于number完成的):number(value)
-
-
-
-
- 数学运算符 先把内容转化为数字再运算
- 字符串 == 数字 先把内容转换为数字再比较
- isNaN('10px') 先把内容转换为数字再检测。数值,返回true,非数值返回false
-
-
-
-
- 弱转化(基于一些额外的方法转换)
-
-
-
-
- parseInt 从左边开始查找数字(整数),遇到到非数字或到达末尾则结束
- parseFloat 从左边开始查找数字(浮点数),遇到到非数字或到达末尾则结束
-
-
-
-
- 需要注意的地方:
- typeof NaN === "number"
- NaN != NaN,它和谁都不相等,包括和自己本身也不相等
-
-
- string
- boolean
- null
- undefined
- symbol
- bigint
- 引用数据类型
-
- object,比如:对象、数组对象、正则对象、日球对象等
- function
数据类型的检测
- typeof 检查数据类型的逻辑运算符
- 返回当前值的数据类型,结果为字符串,如:"object"、"function"、"string"
- 局限性
-
- typeof null --> "object"
- typeof 不能细分对象类型(对象、数组都是"object")
- instanceof 检测是否某个类的实例
- constructor 检测构造函数
- Object.prototype.toString.call 检测数据类型
案例(测试题)
let a = typeof typeof typeof[1,2]
console.log(a)
let b = parseFloat('left:200px')
console.log(b)
let c = 10 + false + undefined + [] + 'haha' + null + true + {}
console.log(c)
parseInt("") //==> NaN
parseInt(null) //==> NaN
parseInt("23px") //==> 23
Number("") //==> 0
Number(false) //==> 0
Number(null) //==> 0
Number("35px") //==> NaN
isNaN("") //==> false
isNaN(null) //==> false
isNaN("43px") //==> true
"12px" + 0 //==> NaN
"12px" == NaN //==> false
parseFloat("2.4px") + parseInt("12.2px") + typeof parseInt(null) //==> "14.4number"
isNaN(Number(!!Number(parseInt("0.8")))) //==> false
typeof !parseInt(null) + !isNaN(null) //==> "booleantrue"