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]

相关推荐
Erishen1 分钟前
🚀 重新定义前端组件安装体验:shadcn + Bun 的极致开发效率
前端
冬奇Lab1 分钟前
Vercel部署全攻略:从GitHub到上线,10分钟让你的前端项目免费拥有自己的域名
前端·后端·node.js
小尧嵌入式2 分钟前
c++红黑树及B树B+树
开发语言·数据结构·c++·windows·b树·算法·排序算法
牛马1114 分钟前
Flutter Web性能优化标签解析
前端·flutter·性能优化
Bigger4 分钟前
Tauri (25)——消除搜索列表默认选中的 UI 闪动
前端·react.js·weui
cike_y5 分钟前
Spring整合Mybatis:dao层
java·开发语言·数据库·spring·mybatis
松涛和鸣9 分钟前
45、无依赖信息查询系统(C语言+SQLite3+HTML)
c语言·开发语言·数据库·单片机·sqlite·html
feifeigo12312 分钟前
基于C#实现即时通讯工具
开发语言·c#
hongkid13 分钟前
React Native 如何打包正式apk
javascript·react native·react.js
李少兄16 分钟前
简单讲讲 SVG:前端开发中的矢量图形
前端·svg