js 面试 1判断变量是否是数组 2 检测数据类型方法

1 是否是数组

  1. typeof 检测数据类型运算符

优点:使用简单

缺点:只能检测基本类型(除null外)

console.log(typeof(10)) //Number

console.log(typeof(false)) //boolean

console.log(typeof('hello')) //string

console.log(typeof([])) // object

console.log(typeof(function(){})) //function

console.log(typeof({})) //object

console.log(typeof(undefined)) //undefined

console.log(typeof(null)) //object

  1. instanceof 检测某个实例是否属于这个类

优点:可以正确判断对象类型(引用类型),内部运行机制是原型链上能否找到这个类型的原型。

缺点:不能正常判断基本类型 并且 不能跨iframe

console.log(100 instanceof Number) //false

console.log('100' instanceof String) //false

console.log(false instanceof Boolean) //false

console.log({} instanceof Object) //true

console.log(function(){} instanceof Function) //true

console.log([] instanceof Array) //true

console.log(/^$/ instanceof RegExp) //true

console.log(/^$/ instanceof Object) //true

前两种比较常用

  1. constructor

优点:基本能检测所有类型(除了null和undefined)

缺点:constructor容易被修改,也不能跨iframe

和instanceof很相似,也能检测出是基本类型,数组,正则。

但constructor检测正则 === Object 检测不出

console.log((10).constructor === Number) //true

console.log(([]).constructor === Array) //true

console.log((function(){}).constructor === Function) //true

console.log(({}).constructor === Object) //true

console.log(/^$/.constructor === RegExp) //true

console.log(/^$/.constructor === Object) //false

  1. Object.prototype.toString.call() 检测数据类型

优点:能检测出所有类型

缺点:在iE6下,undefined和null均为Obj

获取Object原型上的toString方法,让方法执行,并且改变方法中this关键字指向。

let monitor = Object.prototype.toString;

console.log(monitor.call(1)) //[object Number]

console.log(monitor.call('hello')) //[object String]

console.log(monitor.call(null)) //[object null]

console.log(monitor.call(undefined)) //[object undefined]

console.log(monitor.call(function(){})) //[object Function]

相关推荐
Timer@2 分钟前
LangChain 教程 04|Agent 详解:让 AI 学会“自己干活“
javascript·人工智能·langchain
野生技术架构师11 分钟前
2026年牛客网最新Java面试题总结
java·开发语言
环黄金线HHJX.12 分钟前
Tuan符号系统重塑智能开发
开发语言·人工智能·算法·编辑器
dog25012 分钟前
对数的大脑应对指数的世界
开发语言·php
阿珊和她的猫17 分钟前
TypeScript中的never类型: 深入理解never类型的使用场景和特点
javascript·typescript·状态模式
Mr_Xuhhh22 分钟前
深入理解Java抽象类与接口:从概念到实战
java·开发语言
skywalk816338 分钟前
Kotti Next的tinyfrontend前端模仿Kotti 首页布局还是不太好看,感觉比Kotti差一点
前端
萝卜白菜。43 分钟前
TongWeb7.0相同的类指明加载顺序
开发语言·python·pycharm
wb0430720144 分钟前
使用 Java 开发 MCP 服务并发布到 Maven 中央仓库完整指南
java·开发语言·spring boot·ai·maven
Rsun045511 小时前
设计模式应该怎么学
java·开发语言·设计模式