基本用法跟forEach方法类似
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map()返回的是新数组,map() 不会改变原始数组。
语法:
array.map(function(currentValue,index,arr), thisValue)
参数说明:
function(currentValue, index,arr):
必须。函数,数组中的每个元素都会执行这个函数
函数参数:
currentValue 必须。当前元素的值
index 可选。当前元素的索引值
arr 可选。当前元素属于的数组对象
thisValue:
可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。
注意:
function(currentValue, index,arr)回调函数必须要return返回值,不然会返回一个undefind的数组
实际使用的时候,可以利用map方法方便获得对象数组中的特定属性值们。
实例:
var users = [
{name: "熊大", "email": "[email protected]"},
{name: "熊二", "email": "[email protected]"},
{name: "光头强", "email": "[email protected]"}
];
// emails => email的数组
var emails = users.map(function (user) { return user.email; });