一、基本概念
map()方法定义在JavaScript的Array中,它返回一个新的数组,数组中的元素为原始数组调用函数处理后的值。
注意:
1.map()不会对空数组进行检测
2.map()不会改变原始数组
二、语法
array.map(function(currentValue, index, arr), thisIndex)
参数说明:
function(currentValue, index, arr):必须。为一个函数,数组中的每个元素都会执行这个函数。其中函数参数:
1.currentValue:必须。当前元素的的值。
2.index:可选。当前元素的索引。
3.arr:可选。当前元素属于的数组对象。
thisValue:可选。对象作为该执行回调时使用,传递给函数,用作"this"的值。
三、实例
1.两个数组合并成一个数组对象
//1111111111111111111111111111111111111111111111111111111111111111111111111111111111111
// 合并数组对象
let array1 = ['周一','周二','周三','周四','周五','周六','周日']
let array2 = ['上班','上班','出差','出差','团建','休息','约会']
// 将两个数组合并成一个数组并返回
let data = array1.map((item,index) => {
return {
name:item,
value:array2[index]
}
})
console.log('这是合并的数组对象data',data)
data.png
2.返回由原数组中每个元素的平方组成的新数组
//2222222222222222222222222222222222222222222222222222222
let array = [1, 2, 3, 4, 5];
let newArray = array.map((item) => {
return item * item;
})
console.log(newArray) // [1, 4, 9, 16, 25]