语法
array.map(function(currentValue,index,arr), thisValue)
map()
方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。
语法:
callback (执行数组中每个值的函数,包含四个参数)
1. currentValue 必需 (当前元素的值)
2. index可选 (当前元素的索引值)
3. arr 可选 (调用 map 的原数组)
thisValue 可选 (对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。
例子
- 返回数组特定元素相乘的值
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x *2);
console.log(map1);
// [2,8,18,32]
-
返回数组每个元素相乘的值
如果这样写:
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
});
console.log(map1);
// [undefined, 8, undefined, undefined]
为什么会出现三个undefined
,而不是预期的 [1,8,9,16]
。
这样写只是增加了一个条件,即x的值为4时才乘以2,之所以会出现undefined
,是因为map()
方法创建了一个新数组,但新数组并不是在遍历完 array1
后才被赋值的,而是每遍历一次就得到一个值。
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
return x;
});
这样写就正确了