当前位置:网站首页>判断一个变量是数组还是对象?
判断一个变量是数组还是对象?
2022-06-27 17:41:00 【程序员Grand.】
一、变量声明
var arr = []
var obj = {
}
二、判断方式
(1)Array.isArray()
Array.isArray()是ES6提供判断数组的方法,但它有兼容性问题。
Array.isArray(arr) // true
Array.isArray(obj) // false
(2)instanceof 和 constructor
instanceof返回一个布尔值,表示对象是否为某个构造函数的实例。instanceof的左边是实例对象,右边是构造函数,它会检查右边构造函数是否在左边实例对象的原型链上。
原型对象prototype有一个constructor属性,默认指向原型对象prototype所在的构造函数。
console.log(arr instanceof Array); // true
console.log(arr.constructor === Array); // true
但是,instanceof和constructor有弊端。举例如下:
var iframe = document.creatElement('iframe')
document.body.append(iframe)
var xArray = window.frames[window.frames.length - 1].Array
var arr = new xArray(1,2,3)
console.log(a instanceof Array); // false
console.log(a.constructor === Array); // false
(3)Object.prototype.toString.call()
console.log(Object.prototype.toString.call(arr) === '[object Array]') // true
为什么不直接使用obj.toString() === '[object Array]'?
var obj = {
toString:function(){
return '1'
}
}
若对象里重写了toString方法的话,obj.toString() === '[object Array]'为false。
边栏推荐
猜你喜欢

TIA博途_基于SCL语言制作模拟量输入输出全局库的具体方法

Exporting coordinates of points in TXT format in ArcGIS

华大单片机KEIL添加ST-LINK解决方法

别焦虑了,这才是中国各行业的工资真相

《第五项修炼》(The Fifth Discipline):学习型组织的艺术与实践

DFS and BFS simple principle

Keras深度学习实战(12)——面部特征点检测

破解仓储难题?WMS仓储管理系统解决方案

Buzzer experiment based on stm32f103zet6 library function

数仓的字符截取三胞胎:substrb、substr、substring
随机推荐
Seven phases of CMS implementation
让单测变得如此简单 -- spock 框架初体验
Error reported by Huada MCU Keil_ Weak's solution
[notice of the Association] notice on holding summer special teacher training in the field of artificial intelligence and Internet of things
实施MES管理系统前,要对哪些问题进行评估
可靠的分布式锁 RedLock 与 redisson 的实现
maxwell 报错(连接为mysql 8.x)解决方法
Differences between mongodb and MySQL
网络传输是怎么工作的 -- 详解 OSI 模型
Buzzer experiment based on stm32f103zet6 library function
Where to look at high-yield bank financial products?
[cloud based co creation] the "solution" of Digital Travel construction in Colleges and Universities
Market status and development prospect forecast of global aircraft hose industry in 2022
MySQL读取Binlog日志常见错误和解决方法
openssl客户端编程:一个不起眼的函数导致的SSL会话失败问题
New Zhongda chongci scientific and Technological Innovation Board: annual revenue of 284million and proposed fund-raising of 557million
IDEA 官网插件地址
实战回忆录:从Webshell开始突破边界
广发期货开户安全吗?
Exporting coordinates of points in TXT format in ArcGIS