JavaScript Array Object (i): Create, attribute, and detect

Source: Internet
Author: User
Tags javascript array

In fact, online about the array object has a lot of articles, just here to organize themselves, as a sort of knowledge.

Here is a mind map of the array, which feels more detailed (source http://www.cnblogs.com/coco1s/p/3953653.html).

An array is simply an ordered list of data. In the book "The Essence of JavaScript" is described:

An array is a linearly allocated memory that computes offsets and accesses the elements in an integer. An array is a well-performing data structure. Unfortunately, JavaScript does not have the same data structure as such arrays.

As an alternative, JavaScript provides an object that has some class array (array-like) attributes. It transforms the subscript of an array into a string, which is used as a property. It is noticeably slower than a real array, but it is more convenient to use.

I. Creation of arrays

JS creates arrays in two basic ways. One is to use the array constructor, and the other is to use the array literal notation.

/*using the array constructor*/varcolors =NewArray ();//knowing the number of items to be saved in advance, the following code creates an array of length 20varcolors =NewArray (20);//you can also pass to the array constructor the items that should be included in the arraysvarcolors =NewArray ("Red", "Blue", "green");//You can also omit the new operator when using the array constructorvarcolors = Array ("Red", "Blue", "green");varColors = Array (3);/*using array literals notation*/varcolors = ["Red", "Blue", "green"];varnames = [];

There are several areas to note about the creation of arrays:

1. The subscript of an array must be an integer greater than or equal to 0 and less than 2 32 square-1;

2. When using the array literal notation, the array constructor is not called (except Firefox3 and earlier versions);

3.js allows an array to contain values of any mixed type.

Two. Properties of an array
Constructor Specifies the function that creates the object prototype.
Index If the array was created by a regular expression match, the position of the first character of the matched substring in the original string (index starting at 0, read-only).
Input If the array was created from a regular expression match, the original string is returned.
Length Returns the number of elements in an array
Prototype Allow attaching properties to all objects

It may be a bit obscure to look at this form, with a few snippets of code below to illustrate these properties.

1.constructor

Specifies the function that creates the object prototype. The property value is a reference to the function itself, not a string that contains the name of the function. The constructor is a property on the prototype of the constructor, and the following code can be seen

(Note that constructor can be overwritten and used with caution):

varA =NewArray ("A", "B");varb = ["A", "B"];a.__proto__= = = Array.prototype;//trueA.constructor = = = A.__proto__.constructor;//trueA.constructor = = = Array.prototype.constructor;//trueA.constructor = = = Array;//trueb.__proto__= = = Array.prototype;//trueB.constructor = = = B.__proto__.constructor;//trueB.constructor = = = Array.prototype.constructor;//trueB.constructor = = = Array;//true
2.index

If the array was created by a regular expression match, the position of the first character of the matched substring in the original string (index starting at 0, read-only). Not much to say. On the code:

Myre =/d (b +) (d)/i; // EXEC () returns an array that holds the results of the match. If no match is found, the return value is null.
The No. 0 element of this array is the text that matches the regular expression.
The 1th element is the text (if any) that matches the 1th sub-expression of regexpobject.
The 2nd element is the text (if any) that matches the 2nd sub-expression of regexpobject, and so on. //["DBBD", "B5", "D"]//1 because DBBD is starting from 1 of the string index
3.input

If the array was created from a regular expression match, the original string is returned. is a read-only property.

Myre =/d (b +) (d)///["DBBD", "B5", "D"]//"CDBBDBSBZ"
4.length

Returns the number of elements in the array.

var colors = ["Red", "Blue", "green"]; var names =//3names.length; // 0

The length property of an array is not read-only, so by setting this property, you can either remove the item from the end of the array or add a new item to the array. Length Setting the teenager causes all attributes with subscript greater than or equal to the new length to be deleted, and a larger length will not allocate more space to the array, and each new entry will get the undefined value.

var colors = ["Red", "Blue", "green"= 2; colors[//  undefinedcolors;     // ["Red", "blue"] var colors1 = ["Red", "Blue", "green"= 4; colors1[//  undefined colors1;     // ["Red", "Blue", "green", undefined]

There is a more interesting use of the length, by specifying the subscript as the current length of an array, you can append a new element to the end of the array:

var = ["Zero", "one", "numbers"= "Shi"//  ["Zero", "one", " One", "Shi"]
5.prototype

This attribute said too much, is not the focus of the finishing, we can go to view, with a picture under Chrome, version 40.0.2214.94 m:

  

Three. Detecting arrays

When it comes to type detection, it's possible that a lot of people first think of TypeOf, but for an array, typeof returns an "object", which is obviously not for the purpose of detecting the array type. So how to see if a value is an array, let's sort out some of the ways I know it.

1.instanceof and constructor
varIs_array =function(value) {returnValue &&typeofValue = = = ' object ' &&Value.constructor===Array;}; varIs_array1 =function(value) {returnValue &&typeofValue = = = ' object ' &&valueinstanceof Array;};varA =NewArray (All-in-);varb = [A.];is_array (a); //trueIs_array (b);//trueIs_array1 (a); //trueIs_array1 (b);//true

This method should be able to meet the needs in most cases, and compatibility is good. But don't forget, array is the property of window, if the page contains more than one frame, there are actually more than two different global execution environment, so there are more than two different versions of the array constructor. If you pass an array from one frame to another, the incoming array has a different constructor than the array that was created natively in the second frame. In the following case, you can run it in the console to see what it will output:

var myframe = document.createelement (' iframe ');d ocument.body.appendChild (myframe); var myArray = window.frames[window.frames.length-1]. Array; var New // [a,b,10]    instanceof//  false
2.ecmascript5 Array.isarray () method

This method can determine whether a value is an array, regardless of which global execution environment it was created in. Browsers that support this approach are ie9+, Firefox 4+, Safari 5+, Opera 10.5+, and Chrome.

var New Array (+/-); var B = [+ +//  true//  true ]

This method does not have the instanceof method problem, but the compatibility at present still can not satisfy the demand (front-end developers should all understand, said more are tears).

3.object.prototype.tostring

Awaited began to come out, and finally came to this method. Calling the object's native ToString () method on any value returns a string in [object Nativeconstructorname] format. Each class has an internal [[Class]] property, which specifies the name of the constructor in the string above (and of course you can use ({}). toString).

var New Array (All-in-a-box)    ,= [[+],    = // "[Object Array]"//

Since this article only talks about arrays, we'll just give an example of an array. To learn more about the internal principles of this method, you can poke the principle of this link JavaScript:Object.prototype.toString method .

4. Detection methods in some class libraries

Here only some of the approximate implementation, not necessarily can run ha, see the principle is good.

1). JQuery (1.9.1)

varClass2type ={}, core_tostring=Class2type.tostring,jquery.each ("Boolean number String Function Array Date RegExp Object Error". Split (""),function(i, name) {class2type["[Object" + name + "]"] =name.tolowercase ();}); IsArray:Array.isArray||function(obj) {returnJquery.type (obj) = = = "Array";},type:function(obj) {if(obj = =NULL ) {     returnString (obj); }    return typeofobj = = = "Object" | |typeofobj = = = "function"?class2type[Core_tostring.call (obj)]|| "Object" :    typeofobj;}

2). Underscore (1.7.0)

var nativeisarray      =function(obj) {    return tostring.call (obj) = = = ' [Object Array] ';  };

3). Zepto (1.1.6)

IsArray = Array.isarray | |      function return instanceof Array};

Also do not list, basically are based on the above three kinds of methods to deal with, I personally prefer underscore way. Do not know if there is any other way, if there is hope that we can inform, greatly appreciated

Four. Summary

The above is the Array object series of the first article, the main collation of the array of creation, properties and detection problems, my level is limited, inevitably there will be omissions, but also hope that we can advise. The next article will focus on the method of the array.

  

    

    

    

JavaScript Array Object (i): Create, attribute, and detect

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.