Extended Function instances of Array objects in JavaScript programs

Source: Internet
Author: User
We often add custom extension functions to the prototype of String, Function, and Array, such as removing String spaces and sorting arrays. Today we will focus on how to extend Array objects. prototype extension 2. Use your own method to expand the Array object directly in Array. extension on prototype, cannot be directly used for dom objects (such

We often add custom extension functions to the prototype of String, Function, and Array, such as removing String spaces and sorting arrays.

Today I will focus on how to extend Array objects.

1. Extend it directly on Array. prototype

2. Use your own method to expand the array object

It can be expanded directly on Array. prototype and cannot be used directly to dom objects (for example, nodeList obtained by document. getElementsByTagName ('div );

For those with cleanliness, the original ecological environment is also broken :)

First, let's take a look at some methods of yui Operation Array. Here I have stripped and changed the source code.

(Function (){
Var YArray;

YArray = function (o, idx, arraylike ){
Var t = (arraylike )? 2: YArray. test (o ),
L, a, start = idx | 0;
If (t ){
Try {
Return Array. prototype. slice. call (o, start); // use the native method of Array to convert aguments to JS Array
} Catch (e ){
A = [];
L = o. length;
For (; start A. push (o [start]);
}
Return;
}
} Else {
Return [o];
}

}

YArray. test = function (o ){
Var r = 0;
If (o & (typeof o = 'object' | typeof o = 'function ')){
If (Object. prototype. toString. call (o) = "[object Array]") {
R = 1;
} Else {
Try {
If ('length' in o )&&! O. tagName &&! O. alert &&! O. apply ){
R = 2;
}
} Catch (e ){}
}
}
Return r;
}

YArray. each = (Array. prototype. forEach )? // Check whether the browser supports this function. If yes, the native
Function (a, f, o ){
Array. prototype. forEach. call (a | [], f, o | Y );
Return YArray;
}:
Function (a, f, o ){
Var l = (a & a. length) | 0, I;
For (I = 0; I <l; I = I + 1 ){
F. call (o | Y, a [I], I, );
}
Return YArray;
};

YArray. hash = function (k, v ){
Var o ={}, l = k. length, vl = v & v. length, I;
For (I = 0; I If (k [I]) {
O [k [I] = (vl & vl> I )? V [I]: true;
}
}

Return o;
};

YArray. indexOf = (Array. prototype. indexOf )?
Function (a, val ){
Return Array. prototype. indexOf. call (a, val );
}:
Function (a, val ){
For (var I = 0; iif (a [I] = val ){
Return I;
}
}
Return-1; // The result is not found.
};

YArray. numericSort = function (a, B ){
Return (a-B); // sort from small to large, return (B-a); from large to small
};

YArray. some = (Array. prototype. some )?
Function (a, f, o ){
Return Array. prototype. some. call (a, f, o );
}:
Function (a, f, o ){
Var l = a. length, I;
For (I = 0; I If (f. call (o, a [I], I, )){
Return true;
}
}
Return false;
};

})();

Use the native method of Array to convert aguments to other methods of JS Array (Dom object is not allowed, only traversal is allowed)


Array. apply (null, arguments );
[]. Slice. call (arguments, 0 );
[]. Splice. call (arguments, 0, arguments. length );
[]. Concat. apply ([], arguments );
...


The YArray function can operate not only array objects but also nodeList objects.
YArray (document. getElementsByTagName ("div "));
Traverse dom objects and assemble them into an array :)


A = [];
L = o. length;
For (; start A. push (o [start]);
}
Return;


YArray. each
Traverses the array. If a function is input, callback is executed for each traversal.


YArray. each ([1, 2, 3], function (item ){
Alert (item); // three executions, 1, 2, 3
});


YArray. hash
Arrays assembled into key-value pairs can be understood as a json object.
YArray. hash (["a", "B"], [1, 2]);

YArray. indexOf
Returns the index value of this value in the array (to search for a value ).

YArray. indexOf ([1, 2], 1)
YArray. numericSort
Sorts arrays from small to large.
[3, 1, 2]. sort (YArray. numericSort );
YArray. some
Does the element in the array pass the callBack processing? If yes, true is immediately returned. If none of them exist, false is returned.


YArray. some ([3, 1, 2], function (el ){
Return el <4;
})


Let's take a look at the array extensions of javascript 1.6-1.8 and learn how to implement the same functions.
Every
Filter
ForEach
IndexOf
LastIndexOf
Map
Some
Reduce
ReduceRight

Array. prototype. every


If (! Array. prototype. every)
{
Array. prototype. every = 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 ))
Return false;
}
Return true;
};
}


Does each element in the array pass the callBack processing? If yes, true is returned. If one is not, false is immediately returned.
This is similar to some functions of the YUI type we just mentioned: the function is opposite.

Array. prototype. filter


Array. prototype. filter = function (block/*, thisp */) {// filter, easy to add and filter.
Var values = [];
Var thisp = arguments [1];
For (var I = 0; I <this. length; I ++)
If (block. call (thisp, this [I])
Values. push (this [I]);
Return values;
};


Usage


Var val = numbers. filter (function (t ){
Return t <5;
})
Alert (val );


For forEach, indexOf, and some, refer to the above yui code and do not repeat it.
The lastIndexOf code is similar to the indexOf code, but the traversal starts from the end.

Next, let's talk about 'map'


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


Traverse the array, execute functions, and iterate the array. Each element is used as a parameter to execute the callBack method. The callBack method processes each element and returns an array after processing.
Var numbers = [1, 4, 9];
Var roots = numbers. map (function (a) {return a * 2 });

Array. prototype. reduce


Array. prototype. reduce = function (fun/*, initial */){
Var len = this. length >>> 0;
If (typeof fun! = "Function ")
Throw new TypeError ();
If (len = 0 & arguments. length = 1)
Throw new TypeError ();
Var I = 0;
If (arguments. length> = 2 ){
Var rv = arguments [1];
} Else {
Do {
If (I in this ){
Rv = this [I ++];
Break;
}
If (++ I> = len)
Throw new TypeError ();
} While (true );
}
For (; I <len; I ++ ){
If (I in this)
Rv = fun. call (null, rv, this [I], I, this );
}
Return rv;
};


Let the array element call the given function in sequence and return a value. In other words, the returned value must be used for the given function.

Array. prototype. reduceRight
From right to left.


Array. prototype. reduceRight = function (fun/*, initial */){
Var len = this. length >>> 0;
If (typeof fun! = "Function ")
Throw new TypeError ();
If (len = 0 & arguments. length = 1)
Throw new TypeError ();
Var I = len-1;
If (arguments. length> = 2 ){
Var rv = arguments [1];
} Else {
Do {
If (I in this ){
Rv = this [I --];
Break;
}
If (-- I <0)
Throw new TypeError ();
} While (true );
}
For (; I> = 0; I --){
If (I in this)
Rv = fun. call (null, rv, this [I], I, this );
}
Return rv;
};


In addition, all the methods used can be added to Array. prototype.
For example, the commonly used toString


Array. prototype. toString = function (){
Return this. join ('');
};


You can also add toJson, uniq, compact, reverse, etc.
Array Extension is helpful for development :)
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.