ES6中新增了map方法来处理数组,map会将数组中的每个元素传给回调函数,并返回一个新数组。map方法的语法如下:
let newArray = arr.map(function callback(currentValue, index, array) {
// 返回新值
});
callback是遍历数组中每个元素时执行的函数。它接受三个参数:
- currentValue - 数组中正在处理的当前元素
- index - 可选,数组中正在处理的当前元素的索引
- array - 可选,map()被调用的数组 callback函数可以返回任何值,map会把返回的值放到一个新数组中。 示例:
let numbers = [1, 2, 3];
let doubled = numbers.map(function(num) {
return num * 2;
});
console.log(doubled); // [2, 4, 6]
上面代码遍历numbers数组,将每个元素翻倍后返回,map方法将返回的新数组赋值给doubled。 map也可以传递索引:
let numbers = [1, 2, 3];
let doubled = numbers.map(function(num, index) {
return `${index} -> ${num*2}`;
});
console.log(doubled); // ['0 -> 2', '1 -> 4', '2 -> 6']
此外,map方法也支持传入this参数:
let numbers = [1, 2, 3];
let obj = {
multiply: function(num) {
return num * 2;
}
};
numbers.map(function(num) {
return this.multiply(num);
}, obj); // [2, 4, 6]
通过map方法,你可以轻松地处理数组数据,避免繁琐的for循环。