A few days ago to another company interview encountered such a problem, compatible with IE7 under the Array.map method, a face blind. Back to check out the information found. The Array.map method is the newly added method in the ECMA-262 standard, which is wood-in the lower version of JS.
See the following compatibility implementation:
Implementation ideas: 1, first verify the This object, and then wrap this with object as obj.
2, gets the property length of the encapsulated obj
3, verify that there is a callback method
4, the new array (length) is generated based on the property length of obj, Lengh.
5, traverse the Obj object, get Mapkey,mapvalue, and add the return value to the new array in arr.
6, returns the entire new array.
Code implementation:
(function () {if (! Array.prototype.map) {Array.prototype.map = function (callback, args) {var arg, arr, index; if (this = = null) {throw new TypeError (' This was null or not defined '); } var obj = new Object (this);var len = obj >>> 0; Get the length of obj if (Object.prototype.toString.call (callback)! = ' [Object Function] ') {throw new TypeError (callback + ' is not a function '); } if (args) {arg = args; }//Create new array, length as original array o length lenarr = new Array (len);index = 0; While (Index < len) {var kvalue, Mappedvalue;if (index in obj) {//kvalue the value corresponding to the index K.kvalue = Obj[index];//Execute callback,this point to arr with three parameters. Kvalue: Value, index: indexed, obj: the original array.mappedvalue = Callback.call (ARG, kvalue, index, obj);The //return value is added to the new array in arr.Arr[index] = mappedvalue; }index + +; }return arr; } }})()
Array.map method compatible with low version JS