JS的数据类型和判断方式
nys013 2021/7/1 JavaScript面试
# JS的数据类型
在JavaScript中,有七种基本数据类型,分别是:
Number(数字)String(字符串)Boolean(布尔值)Undefined(未定义)Null(空)Symbol(符号,ES6新增)BigInt(大整数,ES11新增)
除了基本数据类型外,JavaScript还有一种复杂数据类型,即对象Object,其中包括Array(数组)和Function(函数)
# 判断数据类型方式
有6种方式:typepf、Array.isArray()、===、constructor、instanceof和Object.property.toString.call()
具体往后看
# 1.typepf
除了无法区分出object,array和null,其他都可判断
// 可区分
typeof(1) // number
typeof('1') // string
typeof(true) // boolean
typeof(undefined) // undefined
typeof(Symbol()) // symbol
typeof(1n) // bigint
typeof(()=>{}) // function
// 不可区分
typeof(null) // object
typeof({}) // object
typeof([]) // object
# 2.Array.isArray()
只能区分出array,其他都不能
// 可区分
Array.isArray([]) // true
// 不可区分
Array.isArray(1) // false
Array.isArray('1') // false
Array.isArray(true) // false
Array.isArray(undefined) // false
Array.isArray(null) // false
Array.isArray(Symbol()) // false
Array.isArray(1n) // false
Array.isArray({}) // false
Array.isArray(()=>{}) // false
# 3.===
可以区分出undefined和null,其他类型都不行
// 可区分
let type1
const type2 = null
console.log(type1 === undefined) // true
console.log(type2 === null) // true
只有null和undefined既是类型也是值,可以使用===判断
# 4.instanceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
即通过实例对象的__proto__一直向上查找,看是否能找到该构造函数的prototype
语法为object instanceof constructor
所以只能判断复杂数据类型Array、Object和Function,其他基本数据类型不能
({}) instanceof Object // true
([]) instanceof Array // true
(()=>{}) instanceof Function // true
但是原型链会一直向上查找,由于Array.prototype和Function.prototype为原型对象,本质上是一个对象,所以再向上找,就能找到Object.prototype
([]) instanceof Object // true
(()=>{}) instanceof Object // true
# 5.constructor
除了undefined和null不能判断,其他类型都可以
(1).constructor === Number // true
'1'.constructor === String // true
true.constructor === Boolean // true
Symbol().constructor === Symbol // true
1n.constructor === BigInt // true
({}).constructor === Object // true
[].constructor === Array // true
(() => {}).constructor === Function // true
# 6.Object.prototype.toString.call()
都可以判断,在任何值上都可以调用 Object 原生的 toString() 方法,会返回一个 [Object NativeConstructorName] 格式的字符串
Object.prototype.toString.call(1) // [object Number]
Object.prototype.toString.call('1') // [object String]
Object.prototype.toString.call(true) // [object Boolean]
Object.prototype.toString.call(undefined) // [object Undefined]
Object.prototype.toString.call(null) // [object Null]
Object.prototype.toString.call(Symbol()) // [object Symbol]
Object.prototype.toString.call(1n) // [object BigInt]
Object.prototype.toString.call({}) // [object Object]
Object.prototype.toString.call([]) // [object Array]
Object.prototype.toString.call(()=>{}) // [object Function]
不过这样的写法比较复杂,得到的结果也需要处理,所以可以定义一个函数来解决
function getType(value) {
return Object.prototype.toString.call(value).match(/^\[object (\w+)\]$/)[1];
}
