Home Web Front-end JS Tutorial Summary of distinguishing between Object and Aarry methods in JS

Summary of distinguishing between Object and Aarry methods in JS

Feb 28, 2017 pm 02:18 PM

1. Frequently encountered problems:

When judging the type of an object in JS, typeof is usually used. At this time, the problem arises, because typeof() returns when identifying an array. object, so judging whether an object is an array in JS

requires some special processing methods. The six processing methods summarized by me are introduced below.

2. Straight to the point

To determine whether an object is an array during development, it is recommended to use the following function:

function isArray(obj){
  if(Array.isArray){
    return Array.isArray(obj);
  }else{
   return Object.prototype.toString.call(obj)==="[object Array]";
  }
}
Copy after login


The above function is convenient for people who are eager to solve problems. I will describe the six methods in detail below, because the examiner may need a comprehensive knowledge of you during the interview;

3. Detailed explanation of the six solutions:

(1) Method 1: Use the toString method

Try to convert the variable into a string representing its type by calling the toString() method. This method is feasible for real arrays; when the parameter object is converted to string

returns [object Arguments], the conversion will fail; in addition, the conversion will also fail for the object class containing a numeric length attribute.

The method is as follows:

nbsp;html>

 
 <title>Array的判断方法</title>
 <meta>
 <script>
	function isArrayOne(arr){
		return <span style="color:#cc0000;">Object.prototype.toString.call(arr) === "[object Array]";
	}
	var obj = {"k1":"v1"};
	var arr = [1,2];
	console.log("对象的结果:"+isArrayOne(obj));
	console.log("数组的结果:"+isArrayOne(arr));
 </script>
 
 
 
 
Copy after login

The result is as shown:

Summary of distinguishing between Object and Aarry methods in JS

Note: It is recommended to use "===" for equals instead of "==" for equals, because it is more efficient!

(2) Method 2: Through isArray:

Using Javascript 1.8.5 (ECMAScript 5), the variable name .isArray() can achieve this purpose, provided that this function is supported. In fact, isArray is the encapsulation of

method one.

The usage is very simple:

Array.isArray(obj); //obj is the object to be detected

Returns true or false, if true, it is an array

(3) Method 3: Judge through the instanceof operator,

Note: The left side of the instanceof operator is the child object (the object to be tested), and the right side is the parent constructor (here is Array),

That is: child object instanceof parent constructor

instance: instance: any object created with new constructor () is called an instance of the constructor

I’ve been confused for a long time, so it’s better to look at the code directly:

nbsp;html>

 
 <meta>
 <meta>
 <meta>
 <meta>
 <meta>
 <title>Document</title>
 <script>
	var obj = {"k1":"v1"};
	var arr = [1,2];
	console.log("Instanceof处理对象的结果:"+(obj instanceof Array));
	console.log("Instanceof处理数组的结果:"+(arr instanceof Array));
 </script>
 
 
 
 
Copy after login

The running results are as follows:

Summary of distinguishing between Object and Aarry methods in JS

(4) Use the isPrototypeOf() function

Principle: Detect whether an object is the prototype of Array (or is in the prototype chain, not only the direct parent object, but also all parent objects on the entire prototype chain can be detected)

Usage: parent.isPrototypeOf(child) to detect whether parent is the prototype of child;

It should be noted that the function implemented by the isPrototypeOf() function is very similar to the instancof operator;

Specific code:

Array.prototype.isPrototypeOf(arr) //true means it is an array, false means it is not an array

(5)Use the constructor

Specific code:

nbsp;html>

 
 <meta>
 <meta>
 <meta>
 <meta>
 <meta>
 <title>Document</title>
 <script>
	var obj = {&#39;k&#39;:&#39;v&#39;};
	var t1 = new Array(1);
	var t2 = t1;
	console.log(obj.constructor == Array);
	console.log(t1.constructor == Array);
	console.log(t2.constructor == Array);
 </script>
 
 
	
 
Copy after login

The result is as shown in the figure

Summary of distinguishing between Object and Aarry methods in JS

(6) Use typeof(object ) + type name combined judgment:

The code is as follows:

nbsp;html>

 
 <meta>
 <meta>
 <meta>
 <meta>
 <meta>
 <title>Document</title>
 <script>
	function isArrayFour(arr){
		if(typeof(arr)==="object"){
			if(arr.concat){
				return "This is Array";
			}else{
				return "This Not Array";
			}
		}
	}
	var arr = [1];
	var obj = {&#39;k&#39;:&#39;v&#39;};
	console.log(typeof(arr));
	console.log(typeof(obj));
	console.log(isArrayFour(arr));
	console.log(isArrayFour(obj));
 </script>
 
 
 
 
Copy after login

The result is as follows:

This method actually has limitations Sex, some students may crack it at once, that is, what if

What if this attribute is accidentally defined in the object

var obj = {'concat':'Teast me?'};
Copy after login

Summary of distinguishing between Object and Aarry methods in JS

The above summary of the six methods of distinguishing Object and Aarry in JS is all the content shared by the editor. I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more articles related to the summary of the JS method of distinguishing Object and Aarry, please pay attention to the PHP Chinese website!


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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Replace String Characters in JavaScript Replace String Characters in JavaScript Mar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup Tutorial Custom Google Search API Setup Tutorial Mar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web Applications Build Your Own AJAX Web Applications Mar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON File Example Colors JSON File Mar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins 8 Stunning jQuery Page Layout Plugins Mar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript? What is 'this' in JavaScript? Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source Viewer Improve Your jQuery Knowledge with the Source Viewer Mar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development 10 Mobile Cheat Sheets for Mobile Development Mar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles