Home > Web Front-end > JS Tutorial > body text

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

高洛峰
Release: 2017-02-06 10:05:43
Original
1447 people have browsed it

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]);
Copy after login

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;
 };
}
Copy after login

Example:



JavaScript Array map Method




Copy after login

This will produce the following results:

roots is : 1,2,3
Copy after login

For more related articles on the use of the map() method for operating arrays in JavaScript, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!