当前位置:网站首页>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]';
};
}
边栏推荐
- Write a program to simulate the traffic lights in real life.
- 杂谈0516
- 4. Branch statements and loop statements
- It's never too late to start. The tramp transformation programmer has an annual salary of more than 700000 yuan
- 3. Input and output functions (printf, scanf, getchar and putchar)
- 自定义RPC项目——常见问题及详解(注册中心)
- FAQs and answers to the imitation Niuke technology blog project (II)
- MySQL lock summary (comprehensive and concise + graphic explanation)
- [the Nine Yang Manual] 2020 Fudan University Applied Statistics real problem + analysis
- 【九阳神功】2016复旦大学应用统计真题+解析
猜你喜欢
C language to achieve mine sweeping game (full version)
hashCode()与equals()之间的关系
Change vs theme and set background picture
Using spacedesk to realize any device in the LAN as a computer expansion screen
[面試時]——我如何講清楚TCP實現可靠傳輸的機制
Safe driving skills on ice and snow roads
MySQL lock summary (comprehensive and concise + graphic explanation)
一段用蜂鸣器编的音乐(成都)
5. Function recursion exercise
ABA问题遇到过吗,详细说以下,如何避免ABA问题
随机推荐
5月14日杂谈
2. First knowledge of C language (2)
(original) make an electronic clock with LCD1602 display to display the current time on the LCD. The display format is "hour: minute: Second: second". There are four function keys K1 ~ K4, and the fun
【九阳神功】2019复旦大学应用统计真题+解析
FAQs and answers to the imitation Niuke technology blog project (III)
20220211-CTF-MISC-006-pure_ Color (use of stegsolve tool) -007 Aesop_ Secret (AES decryption)
C language Getting Started Guide
[中国近代史] 第六章测验
实验五 类和对象
[modern Chinese history] Chapter V test
Wei Pai: the product is applauded, but why is the sales volume still frustrated
【VMware异常问题】问题分析&解决办法
简单理解ES6的Promise
Read only error handling
TypeScript快速入门
Redis的两种持久化机制RDB和AOF的原理和优缺点
【黑马早报】上海市监局回应钟薛高烧不化;麦趣尔承认两批次纯牛奶不合格;微信内测一个手机可注册俩号;度小满回应存款变理财产品...
1.初识C语言(1)
Leetcode.3 无重复字符的最长子串——超过100%的解法
Miscellaneous talk on May 27