如何通过js实现数据类型的准确判断?
- 内容介绍
- 文章标签
- 相关推荐
本文共计629个文字,预计阅读时间需要3分钟。
javascripttypeof 用于判断基本数据类型,如:- typeof 1 // number- typeof '1' // string- typeof true // boolean- typeof Symbol('1') // symbol- typeof undefined // undefined- typeof funct // 'function' (如果 funct 是一个函数)
typeof
一般用于判断基本数据类型,用于判断引用数据类型和null时会发生意外的错误
typeof 1 // number typeof '1' // string typeof true // boolean typeof Symbol('1') // symbol typeof undefined // undefined typeof function(){} // function typeof { a: 1 } // object typeof [1, 2, 3] // object 这里会判断异常,建议使用Array.isArray区分数组和对象 //以下也会判断异常 typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String('abc') === 'object'; //最后来看null typeof null // object
来看下typeof的原理:不同的对象在底层都表示为二进制,在js里二进制前三位都为0的会 被判断为object类型,null的二进制表示全0(对应机器码的null指针,一般为全0),所以会被判断成object类型。
本文共计629个文字,预计阅读时间需要3分钟。
javascripttypeof 用于判断基本数据类型,如:- typeof 1 // number- typeof '1' // string- typeof true // boolean- typeof Symbol('1') // symbol- typeof undefined // undefined- typeof funct // 'function' (如果 funct 是一个函数)
typeof
一般用于判断基本数据类型,用于判断引用数据类型和null时会发生意外的错误
typeof 1 // number typeof '1' // string typeof true // boolean typeof Symbol('1') // symbol typeof undefined // undefined typeof function(){} // function typeof { a: 1 } // object typeof [1, 2, 3] // object 这里会判断异常,建议使用Array.isArray区分数组和对象 //以下也会判断异常 typeof new Boolean(true) === 'object'; typeof new Number(1) === 'object'; typeof new String('abc') === 'object'; //最后来看null typeof null // object
来看下typeof的原理:不同的对象在底层都表示为二进制,在js里二进制前三位都为0的会 被判断为object类型,null的二进制表示全0(对应机器码的null指针,一般为全0),所以会被判断成object类型。

