The method of judging arrays in JavaScript

Source: Internet
Author: User

Summary:

1. Method of array detection:

1) typeof,

2) instanceof,

3) constructor,

4) Object.prototype.toString,

5) Array.isarray ().

These are the methods that are detected for the array, but in these methods:

The Array.isarray () method is the simplest and most convenient method, but there is a version support problem, there is no version support problem and the better detection method is to use the Object.prototype.toString combination call () method to check, In general, it is common practice in array detection to combine the two methods.

The prototype chain, when using the array detection method, we need to have a deep understanding of the prototype chain, in order to know what the actual principle of using the array detection method. About the prototype chain of understanding, you can see I wrote this blog: http://www.cnblogs.com/novice007/p/7764583.html

Constructor, the method of using the constructor to detect the array, which is a large hole, because the constructor can be overridden, so the result is not correct. For example:

1) var arr = [];

Arr.constructor = = = Array; Returns True

2) var arr = ' abc ';

Arr.constructor = Array;

Arr.constructor = = = Array; Returns True

since constructor can be rewritten, it is clear from example 2 that ARR is not an array, but it is overridden by an array, so it returns true.

Introduction to Methods

1.typeof method

The TypeOf method is to determine the type of data. The basic data types in JavaScript are number, NULL, Boolean, String, Array, object, Functionv, undefined, and so on. Its typeof () method detects that the return values are:

1) string, the return value of typeof () is string, for example typeof (' 97900 ') = = "returns a string.

2) function type, the return value of typeof () is function, for example typeof (REGEXP) = = "returns function.

3) The return value of array, object, Null,typeof () is object, such as typeof (null), typeof (document), typeof ([1,3,4,8]) = = Returns an object.

4) Boolean type (Boolean), the return value of typeof () is Boolean, for example typeof (true) = = "Returns a Boolean.

5) number type,the return value of typeof () is numbers, for example, typeof (1) = = "returns #.

6) for undefined variables,the typeof () test results return undefined.

Description: The detection return value of each data type by the TypeOf method above shows that the TypeOf method is not able to accurately detect whether a data is an array, because the TypeOf method detects objects, arrays, and Null by returning object, We are not able to know whether the data is an object or an array. From this we can also learn that storing values with reference types when using the TypeOf operator has some problems, that is, it returns "Object" regardless of what type of object is referenced.

2.instanceof method

The Instanceof method is used to determine whether an object is an instance of the current class, or it can be used in an inheritance relationship to determine whether an instance belongs to its parent type, and the return value is true or false. Here's an example:

1) Console.log (object instanceof object);//true
Console.log (function instanceof function);//true

Console.log (number instanceof number);//false
Console.log (string instanceof string);//false
Console.log (Function instanceof Object);//true

2) The Instanceof method is used in an inheritance relationship to determine whether an instance belongs to its parent type.

function A () {}

function B () {}

B.prototype = new A ();//javascript prototype inheritance

var C = new B ();

Console.log (C instanceof B)//true

Console.log (C instanceof A)//true

Explanation : Here everyone may be more curious, why only the instanceof return value of object and function is true, the other (a instanceof a) return value is false, for this problem, you can Https://www.ibm.com/developerworks/cn/web/1306_jiangjj_

jsinstanceof/ in this article, I see that the use of instanceof in this article is very clear, and I will not explain it here. Instanceof usage is very powerful, but instanceof is not a good way to judge arrays, so let's take a look at the following example:

Window.onload=function () {

Var iframe_arr=new Window.frames[0]. Array;

Alert (iframe_arrinstanceof Array); Returns false

}

The reason for this problem is simply that arrays created in different frameworks (iframe) do not share their prototype properties with each other.

Prototype chain:

The concept of prototype chain is described in ECMAScript, and the basic idea of prototype chain is to use a prototype to inherit the properties and methods of another reference type by referring to the ECMAScript Advanced programming book. The popular prototype chain is a chain-test relationship between a constructor, a prototype and an instance, each of which has a prototype object, and the prototype object contains a pointer to the constructor, and the instance contains a pointer to the inside of the prototype object. For more prototype and prototype chain knowledge I am not here to explain, you can access the information to enter a deeper understanding.

3.constructor method

using The constructor method to determine the principle of an array is because each instance has its corresponding constructor, and we can determine which type it belongs to by judging its constructor function. However, this method is also insufficient, because the constructor can be overridden to make the judgment incorrect, not only that the constructor method has the same problem as the Instanceof method, that the arrays created in different frameworks (IFRAME) do not share their prototype properties with each other. By the following example we can clearly know that the judgment is wrong.

var arr = ' abc ';

Arr.constructor = Array;

Arr.constructor = = = Array; Returns True

4.array.isarray () method

The return value of the Array.isarray () function is Boolean and returns True if the specified argument is an array, otherwise false.

var arr = [];

var res = Array.isarray (arr);//True

var arr = new Array ();

var res = Array.isarray (arr);//True

var arr = [1, 2, 3];

var res = Array.isarray (arr);//True

var res = Array.isarray ("an Array");

document.write (res);//false

Description : This method is a good way to determine arrays, but IsArray () is not supported in the following document modes: Quirks, Internet Explorer 6 standard mode, Internet Explorer 7 Standard mode, Internet Explorer 8 Standard mode. So when using IsArray () to make version judgment, the version supported by the use of this method, when not supported by the use of object.prototype.to

String.call () method, you will then continue to describe the use of the Object.prototype.toString.call () method.

5.object.prototype.tostring.call () method

The principle of this method is to directly output the type (Class) property of the object through the ToString () method transformation.

1) Determine the basic type:

Object.prototype.toString.call (null);//"[Object NULL]"

Object.prototype.toString.call (undefined);//"[Object undefined]"

Object.prototype.toString.call ("abc");//"[Object String]"

Object.prototype.toString.call (123);//"[Object number]"

Object.prototype.toString.call (TRUE);//"[Object Boolean]"

2) Determine the native reference type:

function type

FUNCTION fn () {Console.log ("Test");}

Object.prototype.toString.call (FN);//"[Object Function]"

Date type

var date = new Date ();

Object.prototype.toString.call (date);//"[Object Date]"

Array type

var arr = [n/a];

Object.prototype.toString.call (arr);//"[Object Array]"

Description: Everyone here may be more curious, why not use object.tostring? This is because ToString is a prototype method of object, and the type array, function, and so on as an instance of object, all override the ToString method. When the ToString method is called by different object types, based on the knowledge of the prototype chain, the corresponding overridden ToString method is called (the function type returns a string that contains the body of the functions, and the array type returns the string consisting of the elements ...). Instead of calling the prototype ToString method on object (which returns the concrete type of the object), object.tostring () cannot get its object type, only obj is converted to a string type, so when you want to get the concrete type of the object, The prototype ToString method should be called on object.

Summarize

through the above simple explanation, I believe you can also know clearly, in the array judgment, the best way to judge is The Array.isarray () method and the Object.prototype.toString.call () method, Array.isarray () are the most straightforward array-judging methods, but there are versioning support issues, So we use this method in the case of version compatibility. The Object.prototype.toString.call () method is also a good array-judging method, which solves the problem of cross-iframe invalidation, and there is no version support problem, but uses Object.prototype.toString.call ( is the ideal case where we assume that object.prototype.toString is not rewritten because it is also possible to be rewritten. So through a series of judgments and comparisons, the best way to determine the array is obtained.

var arr1 = [8,4,9];

var arr2 = [{a:1, b:2}];

function IsArray (value) {

if (typeof Array.isarray = = = = "function") {

return Array.isarray (value);

}else{

return Object.prototype.toString.call (value) = = = "[Object Array]";

}

}

Alert (IsArray (ARR1));//True

Alert (IsArray (ARR2));//True

The method of judging arrays in JavaScript

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.