JavascriptArray object use summary_javascript skills

Source: Internet
Author: User
An array is a linear memory allocated. It uses Integers to calculate the offset and access the elements. Arrays are fast data structures, but unfortunately Javascript does not have the same data structure as this array. The array of Javascript is actually an object. It converts the subscript of the array into a string and uses it as an attribute. Therefore, it is obviously slower than the real array, but it can be used more conveniently.

Change your own pop, push, reverse, shift, sort, splice, unshift, without changing your own concat, join, slice, indexOf, lastIndexOf (the last two are 1.6 ), 1.6 new iterators: map, filter, forEach, every, some, 1.8 new reduce, reduceRight
Array object Method

FF: Firefox, N: Netscape, IE: Internet Explorer
Method Description FF N IE
Concat () Add new elements to the array copy and return the new array. The original array is not affected. 1 4 4
Join () Put all elements of the array into a string. The elements are separated by the specified delimiter. 1 3 4
Pop () Delete and return the last element of the array 1 4 5.5
Push () Add one or more elements to the end of the array and return a new length. 1 4 5.5
Reverse () The order of elements in the array is reversed. 1 3 4
Shift () Delete and return the first element of the array 1 4 5.5
Slice () Returns the selected element from an existing array. 1 4 4
Sort () Sorts the elements of an array. An optional parameter is a comparison function. 1 3 4
Splice () Delete elements and add new elements to the array. 1 4 5.5
ToSource () Source code of the object 1 4 -
ToString () Converts an array to a string and returns the result. 1 3 4
ToLocaleString () Converts an array to a local array and returns the result. 1 3 4
Unshift () Add one or more elements to the beginning of the array and return a new length. 1 4 6
ValueOf () Returns the original value of the array object. 1 2 4
Attribute of an Array object
Method Description FF N IE
Index 1 3 4
Input In a normal Array, the input attribute is not available. Only the Array returned after the match () method of the String object is called has the input attribute. It is used to store the content of the original string before matching. 1 3 4
Length Sets or returns the number of elements in the array. 1 2 4
First, let's look at array cloning. Now it is recognized that concat () is the fastest way to clone arrays. In the following tests, we will perform direct traversal and replication, respectively. array. slice (0) and array. concat ()

Script var using R = new Array (100001 ). join ('A '). split (''); var d = new Date (); var bArr = []; for (var I = 0; I <distinct R. length; I ++) {bArr [I] = direction R [I];} alert (new Date ()-d); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


Script var using R = new Array (100001 ). join ('A '). split (''); var d = new Date (); var bArr = partition R. slice (0); alert (new Date ()-d); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


Script var using R = new Array (100001 ). join ('A '). split (''); var d = new Date (); var bArr = partition R. concat (); alert (new Date ()-d); script
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]


Determines whether the object referenced by a variable is an array.

The Code is as follows:


Var isArray = function (){
Return &&
Typeof a === 'object '&&
Typeof a. length = 'number '&&
Typeof a. splice ==== 'function '&&
! (A. propertyIsEnumerable ('length '));
}


This makes arrays computation powerful, which is also very common and should not be used in special financial reports.

The Code is as follows:


Function. prototype. method = function (name, func ){
This. prototype [name] = func;
Return this;
}
Array. method ('reduce', function (fn, value ){
For (var I = 0, l = this. length; I Value = fn (this [I], value );
}
Return value;
});


How to use it, we can create a number array and the related four arithmetic functions, just put them into the reduce function.

The Code is as follows:


Var data = [4, 8, 10, 12, 16]
Var add = function (a, B ){
Return a + B;
}
Var mult = function (a, B ){
Return a * B;
}
// Use
Var sum = data. reduce (add, 0)
Var product = data. reduce (mult, 1 );


The each method allows the elements to execute the passed methods one by one. The corresponding forEach method has been implemented in JavaScript 1.6, but IE does not support it. People have developed a similar each method, which is implemented in various categories of libraries. Let's look at a beautiful implementation (the result of our 51JS Customer Service ):

The Code is as follows:


Array. prototype. each = function (fn ){
For (var I = 0; I This [I]. constructor = Array?
This [I]. each (fn ):
Fn. call (this [I], I );
};
[1, [2, [3, [4, [5, [6, [7, [8, [9, [0]. each (
Function (){
Return alert (this );
});


The above is powerful. In addition to in-depth array traversal, it can also traverse class array objects (such as arguments and NodeList). All attributes of the object will be called by the fn method. But from the perspective of the design model, it has too many responsibilities. the each method should be array-oriented. If it is an object or an array of classes, we should convert them into arrays, such as JQuery makeArray, mootools and Prototype $.

The Code is as follows:


Var arrayize = function (iterable ){
Try {
Return Array. prototype. slice. call (iterable );
} Catch (e ){
Var l = iterable. length | 0, array = new Array (l );
While (l --) array [l] = iterable [l];
Return array;
}
}


Then we can implement the each function of the pure array.

The Code is as follows:


Var each = function (func, array ){
For (var I = 0, l = array. length; I Func (array [I])
}
}


Then change it to a prototype method.

The Code is as follows:


Array. prototype. each = function (func) {each (func, this );};


However, if the browser supports the javascript1.6 forEach method, use forEach

The Code is as follows:


Array. prototype. each = function (func ){
If (Array. prototype. forEach ){
This. forEach (func );
} Else {
Each (func, this );
}
};


Usage:

The Code is as follows:


[4, 5, 6]. each (function (index) {alert (index + "+ 2 =" + (index + 2 ));})


There is also an implementation on the Firefox Official Website:

The Code is as follows:


If (! Array. prototype. forEach)
{
Array. prototype. forEach = function (fun/*, thisp */)
{
Var len = this. length >>> 0;
If (typeof fun! = "Function ")
Throw new TypeError ();
Var thisp = arguments [1];
For (var I = 0; I <len; I ++)
{
If (I in this)
Fun. call (thisp, this [I], I, this );
}
};
}


Let's take a look at the specific implementation of the each method provided by jQuery.
JQuery. each (obj, fn, arg)
This method has three parameters: the object for the operation (obj), the fn function for the operation, and The args parameter of the function.
Let's discuss it based on the ojb object:
1. The obj object is an array.
The each method calls the fn function one by one for the sub-elements of the array until the returned result of a sub-element is false. That is to say, we can process the fn function provided, the each method is called after certain conditions are met. When the each method provides the arg parameter, the incoming parameter of the fn function call is arg. Otherwise, it is a sub-element index and the sub-element itself.
2. The obj object is not an array.
The biggest difference between this method and 1 is that the fn method will be carried out without considering the return value. In other words, all properties of the obj object are called by the fn method, even if the fn function returns false. The input parameters of the call are similar to those of 1.

The Code is as follows:


JQuery. each = function (obj, fn, args ){
If (args ){
If (obj. length = undefined ){
For (var I in obj)
Fn. apply (obj, args );
} Else {
For (var I = 0, ol = obj. length; I <ol; I ++ ){
If (fn. apply (obj, args) = false)
Break;
}
}
} Else {
If (obj. length = undefined ){
For (var I in obj)
Fn. call (obj, I, obj );
} Else {
For (var I = 0, ol = obj. length, val = obj [0]; I <ol & fn. call (val, I, val )! = False; val = obj [++ I]) {}
}
}
Return obj;
}


Note that the call method of fn in the each method does not use simple fn (I, val) or fn (args), but uses fn. call (val, I, val) or fn. apply (obj. args), which means that in your own fn implementation, you can directly use the this pointer to reference arrays or child elements of objects. This is an implementation method adopted by the vast majority of jQuery.

The Code is as follows:


Array. prototype. contains = function (obj ){
Return this. indexOf (obj )! =-1;
};
Array. prototype. copy = function (obj ){
Return this. concat ();
};
Array. prototype. insertAt = function (obj, I ){
This. splice (I, 0, obj );
};
Array. prototype. insertBefore = function (obj, obj2 ){
Var I = this. indexOf (obj2 );
If (I =-1)
This. push (obj );
Else
This. splice (I, 0, obj );
};
Array. prototype. removeAt = function (I ){
This. splice (I, 1 );
};
Array. prototype. remove = function (obj ){
Var I = this. indexOf (obj );
If (I! =-1)
This. splice (I, 1 );
};

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.