ECMAScript5 added some details about the array API
The array Methods Added by ECMAScript5 seem to be relatively simple. In fact, there are still some details that need to be understood. First, these methods do not apply to the original array, and second, they are used to process the sparse array.
(1) These methods do not execute the callback function on the elements missing from the sparse array (2) the returned values of map include the elements missing from the sparse array, the filter method filters out the missing elements of the sparse array and returns a compact array.
var a = new Array(10);a[0] = null ;a[1] = undefined;var _a = a.map(function(){return 1;});console.info(a);//[ null, undefined, , , , , , , , , ]console.info(_a);//[ 1, 1, , , , , , , , , ]_a = a.filter(function(){return true;});console.info(_a);//[ null, undefined ]
In some browsers that do not support these methods, how do we implement these methods? The first problem to be addressed is how to filter out missing elements in the iteration process and use for (var I = 0; I <arr. length; I ++) does not work because the length of an array includes missing elements, in addition, we cannot determine whether this is a missing element or an undefined value intentionally set by undefined, in fact, we can use for in to filter out missing elements.
The following describes how to implement these methods on the browser that does not support these methods.
var each = Array.prototype.forEach ? Array.prototype.forEach : function(callback) { var arr=this; for (var i in arr) { var item = arr[i]; callback.call(item, item, i, arr); } } Array.prototype.each = each; var map = Array.prototype.map ? Array.prototype.map : function(callback) { var arr = this; var _arr = arr.slice(0); for (var i in arr) { var item = arr[i] _arr[i] = callback(item, item); } return _arr; } Array.prototype.map = map; var filter= Array.prototype.filter ? Array.prototype.filter : function(callback) { var r = []; var arr = this; for (var i in arr) { var item = arr[i]; if(callback.call(item, item)) { r.push(item); } } return r; } Array.prototype.filter = filter;