Home >Web Front-end >JS Tutorial >How to use the map() method to operate arrays in JavaScript
The JavaScript array map() method creates a new array using the result of calling the provided function on each element in this array.
Syntax
array.map(callback[, thisObject]);
The following are the details of the parameters:
callback: The function generates new array elements from the current element.
thisObject: The object used as the execution callback
Return value:
Return to create the array
Compatibility:
This method is a JavaScript extends to the ECMA-262 standard; therefore it may not exist in other implementations of the standard. To make it work, you need to add the following script code at the top:
if (!Array.prototype.map) { Array.prototype.map = function(fun /*, thisp*/) { var len = this.length; if (typeof fun != "function") 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; }; }
Example:
JavaScript Array map Method
This will produce the following results:
roots is : 1,2,3
For more related articles on the use of the map() method for operating arrays in JavaScript, please pay attention to the PHP Chinese website!