JavaScript array Array object extension function code _javascript tips

Source: Internet
Author: User
Tags hash javascript array
Let's focus today on how to extend the array object

1, directly on the Array.prototype expansion

2, using their own methods to expand the array of objects

Directly on the Array.prototype, can not directly use the DOM object (such as: document.getElementsByTagName (' div ') to get the nodelist);

For the students who are neat and tidy also broke the original ecological environment:

First look at the Yui operation of the array of methods, here I simply stripped of the source code and changed the next

Copy Code code as follows:

(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); Using the array native method to convert aguments to JS arrays
catch (e) {
a = [];
L = o.length;
for (; start<l; start++) {
A.push (O[start]);
}
return A;
}
} 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)? First detect if the browser has been supported, and if so call 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, a);
}
return yarray;
};

Yarray.hash = function (k, v) {
var o = {}, L = k.length, vl = v && v.length, I;
For (i=0 i<l; i=i+1) {
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; i<a.length; i=i+1) {
if (a[i] = = val) {
return i;
}
}
return-1; The situation that cannot be found
};

Yarray.numericsort = function (A, b) {
return (A-B); From small to large sort, return (B-A); From big 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<l; i=i+1) {
if (F.call (O, a[i], I, a)) {
return true;
}
}
return false;
};

})();



Other methods for converting aguments to JS arrays by using the array native method (DOM objects cannot, only traversal)
Copy Code code as follows:

Array.apply (null,arguments);
[].slice.call (arguments,0);
[].splice.call (Arguments,0,arguments.length);
[].concat.apply ([],arguments);
...


The Yarray function can not only manipulate array objects but also manipulate nodelist objects
Yarray (document.getElementsByTagName ("div"));
To iterate over a DOM object and reassemble it into an array:)
Copy Code code as follows:

a = [];
L = o.length;
for (; start<l; start++) {
A.push (O[start]);
}
return A;

Yarray.each
Iterate over an array, such as an incoming function, that executes callback every traversal
Copy Code code as follows:

Yarray.each ([1,2,3],function (item) {
Alert (item)//executed 3 times, 1,2,3
});

Yarray.hash
Arrays are assembled into key-value pairs that can be understood as a JSON object
Yarray.hash (["A", "B"],[1,2]);

Yarray.indexof
Returns the index value of the array in the same value as the value that you want to find.

Yarray.indexof ([1,2],1)
Yarray.numericsort
Sorting arrays, from small to large
[3, 1, 2].sort (Yarray.numericsort);
Yarray.some
Is there an element in the array that passes through the callback process? If there is, return true immediately, or False if none is available
Copy Code code as follows:

Yarray.some ([3, 1, 2],function (EL) {
Return El < 4;
})


Let's look at the expansion of the JavaScript 1.6-1.8 array and learn how to implement the same functionality
Every
Filter
Foreach
IndexOf
LastIndexOf
Map
Some
Reduce
Reduceright

Array.prototype.every
Copy Code code as follows:

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 through the callback process? If yes, returns True, if one is not, immediately returns false
This and we just mentioned Yui kind of some function is very similar: the function is just the opposite

Array.prototype.filter
Copy Code code as follows:

Array.prototype.filter = function (Block/*, Thisp */) {//filter, easy to add, filter for judgment
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;
};

How to use
Copy Code code as follows:

var val= numbers.filter (function (t) {
return T < 5;
})
Alert (val);

ForEach and IndexOf and some can refer to the above Yui code, no longer repeat
LastIndexOf and IndexOf code are similar only to the last traversal

Let's talk about ' map '
Copy Code code as follows:

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;
};

Iterate over the array, execute the function, iterate the group, each element executes the callback method as a parameter, the callback method processes each element, and finally returns an array of the processed
var numbers = [1, 4, 9];
var roots = Numbers.map (function (a) {return a * 2});

Array.prototype.reduce
Copy Code code as follows:

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 sequentially, and then return a value, in other words, the given function must use the return value

Array.prototype.reduceRight
See the name and think, from right to left
Copy Code code as follows:

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;
};

Except for this, you can add it to the Array.prototype only with the method you want to use.
Like the usual ToString.
Copy Code code as follows:

Array.prototype.toString = function () {
Return This.join (");
};

You can also add Tojson, Uniq, Compact,reverse, etc.
Array extensions are still 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.