js数据类型和Number精讲,轻松搞定面试官
js中的数据类型
-
基本数据类型
- Number
- String
- Boolean
- Null
- Undefined
- Symbol
- BigInt
-
引用数据类型
- object
- 普通对象
- 数组对象 [1,2]
- 正则对象 /\w/g
- 日期对象 new Date()
- Math数学函数 Math.random()
- ...
- function
- object
为什么说function单独的引用数据类型?
所有对象都有__proto__属性,是用来通过__proto__找到它的原型即prototype,function声明的变量的__proto__指向Function的prototype,其它对象的__proto__指向Object的prototype。
数据类型检测
- typeof 检测数据类型的逻辑运算
- instanceof 检测是否为某个类的实例
- constructor 检测构造函数
- Object.prototype.toString.call 检测数据类型的
Number详情
Number的类型
NaN/isNaN/Infinity/parseInt/Number
- NaN: 全称Not A Number,不是有效数字,NaN和谁都不相等,包括它自己
- isNaN: 检测是否为非有效数字,如果不是有效数字返回true,是有效数字返回false。
- 要处理的值不是Number类型时,先转换成Number再检测,比如isNaN("10px") => isNaN(Number("10px")) => isNaN(NaN) => true
- Infinity:默认是无穷大,加负号为无穷小
- parseInt:处理的值是字符串,从字符串左侧开始查找有效数字(遇到非有效数字就停止查找),如果处理的值不是字符串,会先转换成字符串再开始查找有效数字
- Number: 直接调用浏览器最底层的数据类型机制来完成的
- true为1 false 为0
- null为0 undefined为 NaN
- 空字符串为0
- 处理的值为字符串时,必须保证都是有效数字才会转换成数字,否则都是NaN,比如Number("100")为100,Number("100px")为NaN
Number的测试题
parseInt("") // NaN
Number("") // 0
isNaN("") // false 先把""转换成数字,isNaN(0)
parseInt(null) // NaN,先把null转换成字符串,parseInt("null")
Number(null) // 0
isNaN(null) // false,isNaN(0)
parseInt("10px") // 10
Number("10px") // NaN
isNaN("10px") // true,isNaN(NaN)
parseFloat("1.6px")+parseInt("1.2px")+typeof parseInt(null); // "2.6number",1.6+1+"number"
isNaN(Number(!!parseInt("0.8"))) // false
typeof !parseInt(null) + !isNaN(null) // "booleantrue",typeof true + !false => "boolean" + true
想看更多的博客,请到该 博客

浙公网安备 33010602011771号