JS_获取数据类型的三种方式和差别

获取数据类型的三种方式和差别

在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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值