Home >Web Front-end >Front-end Q&A >Is the js map method based on es6?
The map() method is es6. In es6, the map() method can call the specified callback function for each element of the array and return an array containing the results, the syntax is "array.map(function callbackfn (value, index, array), thisArg);". The map() method will return a new array, where each element is the callback function return value of the associated original array element.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Detailed explanation of the map() method in JavaScript (all using es6 syntax)
The JavaScript map() method can map each element of the array Calls the specified callback function and returns 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 return value of map() is a new array, and the elements in the new array are "the values processed by the original array calling function". For each element in the array, the map() method will call the callbackfn function once (in ascending index order), and will not call the callback function for missing elements in the array.
Simple use: traverse the entire array, multiply elements greater than 4 by 2
const array = [2, 3, 4, 4, 5, 6] console.log("array",array) const map = array.map(x => { if (x == 4) { return x * 2 } return x }) console.log("map",map)
The output result is: elements equal to 4 are multiplied by 2
array.map((item,index,arr)=>{ //item是操作的当前元素 //index是操作元素的下表 //arr是需要被操作的元素 //具体需要哪些参数 就传入那个 })
const array = [2, 3, 4, 4, 5, 6] console.log("原数组array为",array) const map2=array.map((item,index,arr)=>{ console.log("操作的当前元素",item) console.log("当前元素下标",index) console.log("被操作的元素",arr) //对元素乘以2 return item*2 }) console.log("处理之后先产生的数组map",map2)
The output result is:
##Summary: map() method is often used to traverse arrays , but the original array will not be changed, but a new array will be returned
Note: Sometimes this phenomenon will occur, with several undefined
const array = [2, 3, 4, 4, 5, 6] console.log("原数组array为",array) const map = array.map(x => { if (x == 4) { return x * 2 } })
In fact, the map() method traverses each item of the array, traverses it once, returns a value, and adds an element to the new array. This is the element that satisfies x=4, and there are only two. So other items return undefined. [Recommended learning:
javascript video tutorial]
The above is the detailed content of Is the js map method based on es6?. For more information, please follow other related articles on the PHP Chinese website!