Home  >  Article  >  Web Front-end  >  How to use the map() method to operate arrays in JavaScript

How to use the map() method to operate arrays in JavaScript

高洛峰
高洛峰Original
2017-02-06 10:05:431408browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn