We often add custom extension functions to the prototypes of String, Function, and Array, such as removing string spaces, sorting arrays, etc.
Today we will focus on how to extend the Array object
1. Expand directly on Array.prototype
2. Use your own method to extend the array object
Expand directly on Array.prototype, it cannot be used directly on DOM objects (such as: nodeList obtained by document.getElementsByTagName('div'));
For those with mysophobia For students, it has also broken the original ecological environment: )
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< ;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 check whether the browser supports it, 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
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
return i;
}
}
return -1; //Cannot be 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
return true;
}
}
return false;
};
})();
Use the Array native method to convert aguments into other JS arrays Methods (Dom objects are not allowed, only traversal)
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 object and reassemble it into an array: )
a = [];
l = o.length;
for (; start
}
return a;
YArray.each
Traverse the array, if there is a function passed in, callback will be executed for each traversal
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 (want to find a value) the same index value of the 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
Whether any elements in the array pass callBack processing? If there is one, it will return true immediately. If there is none, it will return false
YArray.some([3, 1, 2], function(el){
return el < 4;
})
Let’s 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 every 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 the YUI some function we just mentioned:) The function is exactly the opposite. Array.prototype.filter
Array. prototype.filter = function (block /*, thisp */) { //Filter, easy to add, for judgment and filtering
var values = [];
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 Let’s reiterate again
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;
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 is used as a parameter to execute the callBack method, the callBack method processes each element, and finally returns a processed array
var numbers = [1, 4, 9 ];
Array.prototype.reduce
Array.prototype.reduce = function(fun /*, initial*/) {
var len = this.length >>> 0;
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 elements call the given function in sequence , and finally returns a value. In other words, the given function must use the return value
It means the name, from right to left
Array.prototype.reduceRight = function(fun /*, initial*/) {
var len = this.length >>> 0;
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.