当前位置:网站首页>JS several ways to judge whether an object is an array
JS several ways to judge whether an object is an array
2022-07-06 13:50:00 【Ling Xiaoding】
js Several ways to determine whether an object is an array
1. adopt instanceof Judge
instanceof Operator is used to verify the of the constructor prototype Whether the attribute appears anywhere in the object's prototype chain , Returns a Boolean value .
let a = [];
a instanceof Array; //true
let b = {
};
b instanceof Array; //false
Existing problems :
It should be noted that ,prototype Properties can be modified , So it was not initially judged that true It must always be true .
secondly , When our script has multiple global environments , for example html Has more than one iframe object ,instanceof The verification results may not meet the expectations , for example :
// by body Create and add a iframe object
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// obtain iframe Method for constructing an array of objects
xArray = window.frames[0].Array;
// Get an instance through the constructor
var arr = new xArray(1,2,3);
arr instanceof Array;//false
The cause of this problem is iframe Will create a new global environment , It will also have its own Array.prototype attribute , It's obviously unsafe to have the same attributes in different environments , therefore Array.prototype !== window.frames[0].Array.prototype, to want to arr instanceof Array by true, You have to promise arr It's made up of primitive Array Only when the constructor is created .
2. adopt constructor Judge
We know , Constructor property of the instance constructor Pointing constructor , Then through the constructor Property can also determine whether it is an array .let a = [1,3,4];a.constructor === Array;//true
Again , This judgment will also have multiple global environment problems , Resulting problems and instanceof identical .
// by body Create and add a iframe label
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// obtain iframe Method for constructing an array of objects
xArray = window.frames[window.frames.length-1].Array;
// Get an instance through the constructor
var arr = new xArray(1,2,3);
arr.constructor === Array;//false
3. adopt Object.prototype.toString.call() Judge
Object.prototype.toString().call() You can get different types of objects , for example
let a = [1,2,3]
Object.prototype.toString.call(a) === '[object Array]';//true
Its strength lies in that it can not only check whether it is an array , For example, whether it is a function , Is it a number, etc
// Check whether it is a function
let a = function () {
};
Object.prototype.toString.call(a) === '[object Function]';//true
// Check whether it is a number
let b = 1;
Object.prototype.toString.call(a) === '[object Number]';//true
Even for multi global environments , Object.prototype.toString().call() It can also meet the expected processing judgment .
// by body Create and add a iframe label
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
// obtain iframe Method for constructing an array of objects
xArray = window.frames[window.frames.length-1].Array;
// Get an instance through the constructor
var arr = new xArray(1,2,3);
console.log(Object.prototype.toString.call(arr) === '[object Array]');//true
4. adopt Array.isArray() Judge
Array.isArray() Used to determine whether the passed value is an array , Returns a Boolean value .
let a = [1,2,3]
Array.isArray(a);//true
Simple to use , And for multi global environments ,Array.isArray() It can also accurately judge , But there's a problem ,Array.isArray() Is in ES5 It is proposed that , That is to say ES5 This method may not be supported before . How to solve it ?
The final recommendation for judging array methods
Of course, I still use Array.isArray(), from ES5 newly added isArray() Method is to provide a stable and usable array judgment method , It is impossible to put forward good things specifically for this purpose without , And for ES5 Problems that previously did not support this method , In fact, we can do compatibility and self encapsulation , like this :
if (!Array.isArray) {
Array.isArray = function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
}
边栏推荐
- Leetcode. 3. Longest substring without repeated characters - more than 100% solution
- 透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
- Aurora system model of learning database
- 5. Download and use of MSDN
- A comprehensive summary of MySQL transactions and implementation principles, and no longer have to worry about interviews
- 关于双亲委派机制和类加载的过程
- 7-11 机工士姆斯塔迪奥(PTA程序设计)
- [hand tearing code] single case mode and producer / consumer mode
- 附加简化版示例数据库到SqlServer数据库实例中
- Differences among fianl, finally, and finalize
猜你喜欢
随机推荐
6. Function recursion
为什么要使用Redis
Principles, advantages and disadvantages of two persistence mechanisms RDB and AOF of redis
7-15 h0161. 求最大公约数和最小公倍数(PTA程序设计)
(原创)制作一个采用 LCD1602 显示的电子钟,在 LCD 上显示当前的时间。显示格式为“时时:分分:秒秒”。设有 4 个功能键k1~k4,功能如下:(1)k1——进入时间修改。
深度强化文献阅读系列(一):Courier routing and assignment for food delivery service using reinforcement learning
[面试时]——我如何讲清楚TCP实现可靠传输的机制
MySQL事务及实现原理全面总结,再也不用担心面试
实验七 常用类的使用
7-6 矩阵的局部极小值(PTA程序设计)
Implementation of count (*) in MySQL
TypeScript快速入门
Thoroughly understand LRU algorithm - explain 146 questions in detail and eliminate LRU cache in redis
实验六 继承和多态
[the Nine Yang Manual] 2016 Fudan University Applied Statistics real problem + analysis
.Xmind文件如何上传金山文档共享在线编辑?
透彻理解LRU算法——详解力扣146题及Redis中LRU缓存淘汰
The latest tank battle 2022 - full development notes-3
8. C language - bit operator and displacement operator
编写程序,模拟现实生活中的交通信号灯。









