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);".
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:
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:
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!