map()
Array.prototype.map():对数组中到每一项都调用一个提供的函数,将结果返回新到数组返回。
语法:
let new_array = arr.map(function callback(currentValue, index, array) {
// Return element for new_array
}[, thisArg])
复制代码
参数:
callback: 生成新数组元素的函数,使用三个参数:
- currentValue: callback的第一个参数,数组中正在处理的当前元素。
- index: callback 的第二个参数,数组中正在处理的当前元素的索引。
- array:* callback 的第三个参数,map 方法被调用的数组。
thisArg: 可选的。执行 callback 函数时 使用的this 值。
描述:
map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数。callback 每次执行后的返回值(包括 undefined)组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。
callback 函数会被自动传入三个参数:数组元素,元素索引,原数组本身。
如果 thisArg 参数有值,则每次 callback 函数被调用的时候,this 都会指向 thisArg 参数上的这个对象。如果省略了 thisArg 参数,或者赋值为 null 或 undefined,则 this 指向全局对象 。
map 不修改调用它的原数组本身(当然可以在 callback 执行时改变原数组)。
使用 map 方法处理数组时,数组元素的范围是在 callback 方法第一次调用之前就已经确定了。在 map 方法执行的过程中:原数组中新增加的元素将不会被 callback 访问到;若已经存在的元素被改变或删除了,则它们的传递到 callback 的值是 map 方法遍历到它们的那一时刻的值;而被删除的元素将不会被访问到。
例子:
let arr = [1, 2, 3]
let newArray = arr.map((item, index, array) => {
item + 1
// array[index] === item ture
})
console.log(newArray) // [2, 3, 4]
复制代码
实际使用:
一般我们在对json数据进行转换到时候(数据适配器)会使用比较多
let arr = [
{
id: 1,
name: 'wxw',
age: 22
},
{
id: 2,
name: 'mxm',
age: 27
},
{
id: 1,
name: 'dzw',
age: 9
}
]
let newArray = arr.map((item) =>{
item.id = item.id + 1
item.lastName = item.name + 'hello'
})
console.log(newArray)
结果:
let newArray = [
{
id: 2,
name: 'wxw',
age: 22,
lastName: 'wxwhello'
},
{
id: 3,
name: 'mxm',
age: 27,
lastName: 'mxmhello'
},
{
id: 4,
name: 'dzw',
age: 9,
lastName: 'dzwhello'
}
]
复制代码
字符串反序也是经常使用到的需求
let str = 'hello word'
let ss = Array.prototype.map.call(str, (item) =>{
return item
}).reverse().join('')
console.log(ss) // drow olleh
复制代码