Array.map method compatible with low version JS

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.