Home  >  Article  >  Web Front-end  >  What does the es6 map() method do?

What does the es6 map() method do?

青灯夜游
青灯夜游Original
2021-09-29 17:32:477897browse

In es6, the map() method is used to call the specified callback function for each element in the array and return an array containing the results; the syntax "array.map(function callbackfn (value, index , array), thisArg);".

What does the es6 map() method do?

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

JavaScript map() method can call the specified callback function for each element of the array and return an array containing the results.

array.map(function callbackfn (value, index, array), thisArg);

function callbackfn (value, index, array): A callback function that accepts up to three parameters:

  • value: array element value.

  • index: Numeric index of the array element.

  • array: Array object containing the element.

The map() method will return a new array, where each element is the callback function return value of the associated original array element. For each element in the array, the map() method calls the callbackfn function once (in ascending index order) and does not call the callback function for missing elements in the array.

In addition to array objects, the map() method can be used by any object with a length property and an indexed property name, such as an Arguments parameter object.

Let’s learn more about it through code examples:

Example 1: Double all element values ​​(that is, multiply by 2)

var a = [30,40,50];
function f(value) {
	return value*2;
}
var a1=a.map(f);
console.log(a1);

Output results:

What does the es6 map() method do?

Example 2: Using JavaScript built-in methods as callback functions

var a = [9, 16];
var a1 = a.map(Math.sqrt);
console.log(a1);  //3,4

Output results:

What does the es6 map() method do?

Related recommendations :javascript video tutorial

The above is the detailed content of What does the es6 map() method do?. For more information, please follow other related articles on 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