How to determine whether a data is an array

WBOY
Release: 2024-01-08 08:06:17
forward
1142 people have browsed it

How to determine whether a data is an array

There are two main ones, typeof and instanceof, juti usage is as follows

typeof operator

For several types of objects such as Function, String, Number, Undefined, etc., he is fully capable, but for Array

1 var arr=new Array("1","2","3","4","5");

2 alert(typeof(arr));

You will receive an object answer, which is a bit disappointing.

instanceof operator

The instanceof operator in JavaScript returns a Boolean value indicating whether the object is an instance of a specific class. Usage method: result = object instanceof class, still the array just now, try it again, um, return true successfully.

1 var arrayStr=new Array("1","2","3","4","5");

2 alert(arrayStr instanceof Array);

Small summary: It seems that the questions we discussed today have been answered, but in fact, shuttling between multiple frames will cause big problems.

Four ways to determine whether a variable is an array or an object in js

Because whether it is an array or an object, the return value of the typeof operation is object, so there is a need to distinguish between array types and object types:

Fang 1: Through the length attribute: Generally, the object does not have a length attribute value, its value is undefiend, and the length value of the array is of type number

Disadvantages: Very impractical. When the object's attribute has length and its value is number (such as a class array), this method will be invalid. It is not recommended to use it. Just take a look.

*Part 2: Judge the distinction through instanceof

var arr = [1, 2, 3]; var obj = {name: 'lyl',age: 18, 1: 'name'}console.log(arr instanceof Array); //trueconsole.log(obj instanceof Array); //false

*Fang San: through constructor

var arr = [1, 2, 3]; var obj = {name: 'lyl',age: 18, 1: 'name'}console.log(arr.constructor === Array); //trueconsole .log(obj.constructor === Array); //false

The above is the detailed content of How to determine whether a data is an array. For more information, please follow other related articles on the PHP Chinese website!

source:docexcel.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!