JavaScript判断变量是否为某种类型
本文最后更新于:2022年10月12日 上午
对象、数组
判断是否为对象
const obj = {};
Object.prototype.toString.call(obj) === '[object Object]'
[object Object]
中第一个o小写obj.constructor === Object
obj instanceof Object
(不可行)数组和函数也会返回true
typeof obj === Object
(不可行)存在特殊情况,
typeof
一般用于判断原始值1
2
3
4
5typeof undefined //'undefined'
typeof null //'object'
typeof function() {} //'function'
typeof {} //'object'
typeof [] //'object'$.isPlainObject(obj)
判断指定参数是否为一个纯粹的对象(指该对象是通过
{}
或new Object()
创建的)
判断是否为数组
const arr = [];
Object.prototype.toString.call(arr) == '[object Array]'
typeof obj == 'object' && arr.constructor === Array
obj instanceof Array
typeof arr //'object'
(不可行)Array.isArray()
使用
instanceof
方法和constructor
属性判断时,如遇到跨框架(iframe
),在不同的框架中,创建的数组不共享其prototype属性,无法准确判断
JavaScript判断变量是否为某种类型
https://elcfin.github.io/2021/11/09/判断是否为对象-数组/