获取数据类型的三种方式和差别
在JavaScript中,获取数据类型的方式主要有三种:typeof运算符、instanceof运算符和Object.prototype.toString.call()方法。以下是它们的使用方式和差别:
typeof运算符:
使用方式:typeof variable
优点:简单易用,可以快速地检测基本数据类型。
缺点:对于复杂数据类型(如数组、对象、函数等)的检测可能会出现误判。例如,typeof []会返回"object",而不是"array"。
typeof '' // string
typeof 0 // number
typeof {} // object
typeof [] // object
instanceof运算符:
使用方式:variable instanceof Constructor
优点:可以用来检测对象是否是特定构造函数创建的实例。
缺点:只能用于检测对象类型,对于基本数据类型无效。
function Person(name) {
this.name = name;
}
const john = new Person('John');
console.log(john instanceof Person); // true
console.log(john instanceof Object); // true
console.log(john instanceof Array); // false
Object.prototype.toString.call()方法:
使用方式:Object.prototype.toString.call(variable)
优点:准确度高,能够准确地检测出复杂数据类型的类型。
缺点:相对于前两种方式来说,使用上稍微复杂一些。
在大多数情况下,推荐使用Object.prototype.toString.call()方法来获取数据类型,因为它能够提供最准确的结果。如果需要检测基本数据类型,可以使用typeof运算符。而instanceof运算符则主要用于检测对象是否是特定构造函数创建的实例。
function getDataType(target) {
let type = typeof target
if (type === 'object') {
return Object.prototype.toString.call(target).replace(/^[object (\S+)]$/, '$1').toLowerCase()
} else {
return type
}
}
getDataType('') // string
getDataType(0) // number
getDataType([]) // [object array]
getDataType({}) // [object object]
getDataType(()=>{}) // function