ECMAScript5 New Array method seems to be relatively simple in fact, there are some details need to understandFirst of all, these methods are not used in the original array, followed by the processing of the sloppy array.
(1) These methods do not execute the callback function on the missing elements of the sloppy Array (2) The return value of map includes the missing elements of the sloppy array, and the filter method filters out the missing elements of the array, thus returning a compact array
var a = new Array (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 (fu Nction () {return true;}); Console.info (_a);//[null, undefined]
How do we implement these methods in some viewers that do not support these methods? The first thing to deal with is how to filter out missing elements in the iterative process, using the for (var i = 0; i < arr.length; i++) loop method, because the length of the array is the one that includes the missing elements. , and we can not undefined to determine whether this is a missing element or deliberately set the undefined value, in fact, think of the particularity of JS array This problem is still very good solution we can filter out missing elements directly
Here's how we do it ourselves on a browser that doesn't 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;
ECMAScript5 Some details of the new array API