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

相关推荐
DianSan_ERP34 分钟前
电商架构演进:如何在高并发场景下实现多平台API的标准化履约?
运维·前端·网络·安全·架构·自动化
殳翰37 分钟前
下服务器端开发流程及相关工具介绍(C++)
开发语言·c++
落寞的星星1 小时前
这个对象就包含了已经转换好的DFA和各种词法分析器运转所需要的参数。下一步,我们就可以用ScannerInfo对象创建出Scanner对象,请看下面的代码:
开发语言·c#
nothing&nowhere1 小时前
用 Python 做问卷数据清洗:无效样本检测与处理实战
开发语言·python·数据清洗·数据处理·问卷星·问卷星脚本·刷问卷
2601_961593422 小时前
Rust 开发环境配置繁琐?RustRover 开箱即用搞定编码调试
开发语言·后端·macos·rust
HZZD_HZZD2 小时前
DL/T 645-2026新国标深度解读与智能电表协议适配实战:从帧结构变化到Java采集器升级的全链路改造方案
java·开发语言
碎_浪3 小时前
给键盘党的英语记忆工具:我做了一款「打字背单词」桌面应用
前端·程序员·ai编程
阿成学长_Cain4 小时前
Linux dirs命令详解|Bash目录堆栈管理快速切换目录实战教程
linux·运维·前端·数据库
多加点辣也没关系5 小时前
JavaScript|第4章:类型转换
开发语言·javascript
聪慧的水蜜桃5 小时前
【YFIOs】用C#开发硬件之设备上云
开发语言·c#