javascript如何检测数据类型_typeof和instanceof有何区别【教程】

技术百科 紅蓮之龍 发布时间:2026-01-28 浏览:
typeof 对 null 返回 "object"(历史 bug),对数组、普通对象、正则、日期等均返回 "object",仅对函数返回 "function";instanceof 依赖原型链,跨 iframe 失效且无法检测原始值。

typeof 适合快速判断基本类型,但对 null 和对象(包括数组、正则、日期等)一律返回 "object"instanceof 可识别引用类型的构造器来源,但依赖原型链,跨 iframe 失效。

typeof 对哪些值返回意外结果?

它在几个关键地方“不准”:

  • typeof null 返回 "object"(历史 bug,已成标准)
  • typeof []typeof {}typeof /reg/typeof

    new Date()
    全是 "object"
  • typeof function() {} 返回 "function"(这是特例,不是标准对象)
  • typeof Symbol() 返回 "symbol"typeof BigInt(1) 返回 "bigint"(ES6+ 新增,表现正常)

instanceof 的原理和典型失效场景

它本质是检查 left.__proto__ 是否沿原型链能找到 right.prototype。因此:

  • 能正确区分 [] instanceof Arraytrue)、{} instanceof Objecttrue)、/a/ instanceof RegExptrue
  • let iframe = document.createElement('iframe'); document.body.appendChild(iframe); let arr = iframe.contentWindow.Array; [] instanceof arr 返回 false(不同全局环境,原型链断裂)
  • 无法检测原始值:123 instanceof Numberfalse(数字字面量不是实例)

更可靠的类型检测方案(推荐组合)

单靠一个操作符不够,常用补救方式:

  • 判空先用 value === null,再用 typeof value === "object" 避开 null 陷阱
  • 检测数组优先用 Array.isArray(value)(最准,ES5+ 支持)
  • 检测内置对象统一走 Object.prototype.toString.call(value)
    Object.prototype.toString.call([])   // "[object Array]"
    Object.prototype.toString.call(/a/) // "[object RegExp]"
    Object.prototype.toString.call(null) // "[object Null]"
  • 自定义类可用 instanceof,但注意避免跨上下文使用

真正难的不是记住区别,而是意识到:JavaScript 没有“类型系统”的强契约,所有检测都是基于运行时结构的推测——所以别依赖单一手段,尤其在处理第三方数据或跨环境对象时。


# 几个  # 意识到  # 都是  # 它在  # 这是  # 自定义  # 能找到  # app  # 已成  # 再用  # win  # 对象  # javascript  # java  # 区别  # typeof  # function  # bug  # NULL  # 数据类型  # 引用类型  # Object  # date  # Array  # 但对  # number  # es6  # symbol  # regexp  # prototype  # iframe 


相关栏目: <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 AI推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 SEO优化<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 技术百科<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 谷歌推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 百度推广<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 网络营销<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 案例网站<?muma echo $count; ?> 】 <?muma $count = M('archives')->where(['typeid'=>$field['id']])->count(); ?> 【 精选文章<?muma echo $count; ?>

相关推荐

在线咨询

点击这里给我发消息QQ客服

在线咨询

免费通话

24h咨询:4006964355


如您有问题,可以咨询我们的24H咨询电话!

免费通话

微信扫一扫

微信联系
返回顶部