通用的检测数据类型方法

本文深入探讨了JavaScript中的`instanceof`、`typeof`操作符以及`Object.prototype.toString`方法在确定变量类型和原型链中的应用。通过示例展示了如何判断对象实例、基本类型以及非对象实例,并解释了`typeof`对于`null`的特殊处理。同时,文章还利用`toString`方法来获取数据类型的字符串表示,揭示了其在类型检测中的作用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、instanceof

var simpleStr = "This is a simple string";
var myString  = new String();
var newStr    = new String("String created with constructor");
var myDate    = new Date();
var myObj     = {};
var myNonObj  = Object.create(null);

simpleStr instanceof String; // 返回 false, 非对象实例,因此返回 false
myString  instanceof String; // 返回 true
newStr    instanceof String; // 返回 true
myString  instanceof Object; // 返回 true

myObj instanceof Object;    // 返回 true, 尽管原型没有定义
({})  instanceof Object;    // 返回 true, 同上
myNonObj instanceof Object; // 返回 false, 一种创建非 Object 实例的对象的方法

myString instanceof Date; //返回 false

myDate instanceof Date;     // 返回 true
myDate instanceof Object;   // 返回 true
myDate instanceof String;   // 返回 false

2、typeof

注意:typeof null 返回 "object"

操作符返回一个字符串,表示未经计算的操作数的类型
typeof只能判断对象类型中的function,其它都为objecct

3、object原型链上的toString方法

const a = {}
const b = {}
const c = {}

b[a] = 1
b[c] = 2

console.log(b[a]) //2

console.log(Object.prototype.toString.call(this)) //[object Object]
console.log(a.toString()) //[object Object]

const fn = function () {}
console.dir(fn.__proto__)
console.log(fn.__proto__.toString) //ƒ toString() { [native code] }
console.log(Function.prototype.toString) //ƒ toString() { [native code] }

function getDataType(data) {
  const type = Object.prototype.toString.call(data)
  return console.log(type.substring(8, type.length - 1))
}

getDataType({}) //Object
getDataType([]) //Array
getDataType(true) //Boolean

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值