当前位置:网站首页>判断变量是否为数组
判断变量是否为数组
2022-07-05 13:57:00 【前端西瓜哥】
大家好,我是前端西瓜哥,今天带大家学习在 JS 中如何判断一个对象是否为数组。
Array.isArray
最好的写法是使用 Array.isArray(val)。
因为该方法能正确判断 iframe 传过来的变量。
instanceof
val instanceof Array
对于一个普通数组,它的原型链是这样的:
数组实例 -> Array.protype -> Object.prototype -> null
如果一个变量是数组,那它的原型链上就一定会有 Array.prototype。
instanceof 的原理其实就左值沿着它的原型链,和右侧值的 prototype 属性比较,看是否相等。找到相等的就返回 true,否则返回 false。
但 instanceof 无法处理 iframe 的变量,因为 iframes 的 Array 并不是当前页面的 Array,它们指向各自的内存空间。
const iframe = document.createElement('iframe');
document.body.appendChild(iframe);
const ArrayInFrame = window.frames[0].Array; // iframe中的构造函数
const arr = new ArrayInFrame();
arr instanceof Array // false
Array.isArray(arr); // true
只要是能判断 对象是否在原型链上 的方法都是可以的用来判断是否为数组的,所以你还可以用:
// isPrototypeOf 方法
// Array.prototype 是否在 val 的原型链上
Array.prototype.isPrototypeOf(val);
// getPrototypeOf 方法
// val 的上一个原型是否为 Array.prototype
Object.getPrototypeOf(val) === Array.prototype
Object.prototype.toString.call
Object.prototype.toString.call(val) === '[object Array]';
对象都可以通过 toString 方法生成一个字符串,对于对象,通常会返回 [object Xxx] 的形式的字符串,对于数组,则会返回 [object Array]。
结尾
考虑到要兼容 iframe 的变量,所以建议使用 Array.isArray 方案。
此外判断数组还可以使用查找原型链对象的方法,以及通过 toString 得到的字符串的方法。
我是前端西瓜哥,欢迎关注我,掌握更多前端面试题。
边栏推荐
- upload (1-6)
- 清大科越冲刺科创板:年营收2亿 拟募资7.5亿
- 昆仑太科冲刺科创板:年营收1.3亿拟募资5亿 电科太极持股40%
- UE source code reading [1]--- starting with problems delayed rendering in UE
- 鸿蒙第四次培训
- 瑞能实业IPO被终止:年营收4.47亿 曾拟募资3.76亿
- Attack and defense world web WP
- 搭建一个仪式感点满的网站,并内网穿透发布到公网 2/2
- 2022年机修钳工(高级)考试题模拟考试题库模拟考试平台操作
- Ordering system based on wechat applet
猜你喜欢

Convolutional Neural Networks简述

金融壹账通香港上市:市值63亿港元 叶望春称守正笃实,久久为功

Anchor navigation demo

LeetCode_2(两数相加)

Kotlin协程利用CoroutineContext实现网络请求失败后重试逻辑

Laravel dompdf exports PDF, and the problem of Chinese garbled code is solved

Summit review | baowanda - an integrated data security protection system driven by compliance and security

:: ffff:192.168.31.101 what address is it?
![[cloud resources] what software is good for cloud resource security management? Why?](/img/c2/85d6b4a956afc99c2dc195a1ac3938.png)
[cloud resources] what software is good for cloud resource security management? Why?

RK3566添加LED
随机推荐
MySQL if else use case use
Linked list (simple)
NFT value and white paper acquisition
Deep copy is hard
Convolutional Neural Networks简述
物联网应用技术专业是属于什么类
Log4j utilization correlation
Anchor navigation demo
LeetCode_67(二进制求和)
uplad_ Labs first three levels
Simple process of penetration test
Sqllab 1-6 exercise
瑞能实业IPO被终止:年营收4.47亿 曾拟募资3.76亿
Can graduate students not learn English? As long as the score of postgraduate entrance examination English or CET-6 is high!
蓝桥杯学习2022.7.5(上午)
锚点导航小demo
【公开课预告】:视频质量评价基础与实践
UE source code reading [1]--- starting with problems delayed rendering in UE
IP packet header analysis and static routing
Basic characteristics and isolation level of transactions