Today we will focus on how to extend the Array object
1. Extend
directly on Array.prototype 2. Use your own method to extend the array object
directly on Array. Extended on prototype, it cannot be used directly on DOM objects (such as: nodeList obtained by document.getElementsByTagName('div'));
It also breaks the original ecological environment for students with mysophobia: )
Let’s first look at some methods of yui operating arrays. Here I simply 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 Array native method to convert atoms into JS array
} catch(e) {
a = [];
l = o.length;
for (; 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 check whether the browser supports it , 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; iif (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; //Cannot find situation
};
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; iif (f. call(o, a[i], i, a)) {
return true;
}
}
return false;
};
})() ;
Use the Array native method to convert objects into JS arrays (Dom objects cannot, only traverse)
Array.apply(null,arguments);
[].slice.call(arguments,0) ;
[].splice.call(arguments,0,arguments.length);
[].concat.apply([],arguments);
...
The YArray function can not only operate on array objects but also on nodeList objects
YArray(document.getElementsByTagName("div"));
Traverse the dom objects and reassemble them into an array: )
a = [];
l = o.length;
for (; starta.push(o[start]);
}
return a;
YArray.each
Traverse Array, if there is a function passed in, callback will be executed every time it is traversed
YArray.each([1,2,3],function(item){
alert(item); // Executed 3 times, 1,2,3
});
YArray.hash
The array is assembled into key-value pairs and can be understood as a json object
YArray.hash(["a","b"],[1,2]);
YArray.indexOf
Returns (the value you want to find) the same index value in the array
YArray.indexOf([1,2],1)
YArray.numericSort
Sort the array from small to large
[3, 1, 2].sort(YArray.numericSort);
YArray.some
Have any elements in the array passed callBack processing? If there is, it will return true immediately, if there is none, it will return false
YArray.some([3, 1, 2],function(el){
return el < 4;
})
Let We look at the JavaScript 1.6 -1.8 extensions to arrays and learn how to implement the same functionality
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;
};
}
Has each element in the array been processed by callBack? If it is, it returns true. If one of them is not, it returns false immediately
This is very similar to some of the YUI functions we just mentioned:) The function is just the opposite
Array.prototype.filter
Array.prototype.filter = function (block /*, thisp */) { //Filter, easy to add, for judgment filtering
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);
forEach and indexOf and some can refer to the yui code above, no To reiterate,
lastIndexOf and indexOf codes are similar, just traverse from the end
Now 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 the function, iterate the array, each element executes the callBack method as a parameter, the callBack method processes each element, and finally returns A processed array
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 array The elements call the given function in sequence, and finally return a value. In other words, the given function must use the return value
Array.prototype.reduceRight
as the name implies, 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 to these, any method you want to use 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 still very helpful for development: )