語法
array.map(function(currentValue,index,arr), thisValue)
map()方法創(chuàng)建一個新數(shù)組,其結(jié)果是該數(shù)組中的每個元素都調(diào)用一個提供的函數(shù)后返回的結(jié)果。
語法:
callback (執(zhí)行數(shù)組中每個值的函數(shù),包含四個參數(shù))
1. currentValue 必需 (當(dāng)前元素的值)
2. index可選 (當(dāng)前元素的索引值)
3. arr 可選 (調(diào)用 map 的原數(shù)組)
thisValue 可選 (對象作為該執(zhí)行回調(diào)時使用,傳遞給函數(shù),用作 "this" 的值。
如果省略了 thisValue,或者傳入 null、undefined,那么回調(diào)函數(shù)的 this 為全局對象。
例子
- 返回數(shù)組特定元素相乘的值
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x *2);
console.log(map1);
// [2,8,18,32]
-
返回數(shù)組每個元素相乘的值
如果這樣寫:
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
});
console.log(map1);
// [undefined, 8, undefined, undefined]
為什么會出現(xiàn)三個undefined,而不是預(yù)期的 [1,8,9,16]。
這樣寫只是增加了一個條件,即x的值為4時才乘以2,之所以會出現(xiàn)undefined,是因為map()方法創(chuàng)建了一個新數(shù)組,但新數(shù)組并不是在遍歷完 array1 后才被賦值的,而是每遍歷一次就得到一個值。
var array1 = [1, 4, 9, 16];
const map1 = array1.map(x => {
if (x == 4) {
return x * 2;
}
return x;
});
這樣寫就正確了