当前位置:网站首页>判断一个变量是数组还是对象?
判断一个变量是数组还是对象?
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。
边栏推荐
猜你喜欢

Erreur Keil de Huada Single Chip Computer La solution de Weak

工作流自动化 低代码是关键

基于STM32F103ZET6库函数外部中断实验

Blink SQL内置函数大全

Summary of domestic database certification test guide (updated on June 16, 2022)

Bit.Store:熊市漫漫,稳定Staking产品或成主旋律

A simple calculation method of vanishing point

Bit. Store: long bear market, stable stacking products may become the main theme

PCB线路板蛇形布线要注意哪些问题?

Error reported by Huada MCU Keil_ Weak's solution
随机推荐
【云驻共创】 什么是信息化?什么是数字化?这两者有什么联系和区别?
惊呆!原来 markdown 的画图功能如此强大!
Teach you how to install Oracle 19C on Windows 10 (detailed picture and text with step on pit Guide)
基于STM32F103ZET6库函数外部中断实验
CDGA|交通行业做好数字化转型的核心是什么?
破解仓储难题?WMS仓储管理系统解决方案
DFS and BFS simple principle
通过 G1 GC Log 重新认识 G1 垃圾回收器
校园书籍资源共享平台
Campus book resource sharing platform
im即时通讯开发之双进程守护保活实践
Implementation of reliable distributed locks redlock and redisson
Cloud native database: the outlet of the database, you can also take off
实战回忆录:从Webshell开始突破边界
买股票在券商经理的开户链接上开户安全吗?求大神赐教
一对一关系
[elt.zip] openharmony paper Club - memory compression for data intensive applications
谈谈线程安全
Common errors and solutions of MySQL reading binlog logs
Online text batch inversion by line tool