map()
方法通过对每个数组元素调用一个 函数,然后将此函数返回的新值组合成一个新数组。
示例
let numbers = [2, 4, 6, 8, 10];
// function to return the square of a number
function square(number) {
return number * number;
}
// apply square() function to each item of the numbers list
let square_numbers = numbers.map(square);
console.log(square_numbers);
// Output: [ 4, 16, 36, 64, 100 ]
map() 语法
map()
方法的语法是
arr.map(callback(currentValue), thisArg)
这里,arr 是一个数组。
map() 参数
map()
方法接受
- callback - 为每个数组元素调用的函数。它的返回值被添加到新数组中。它接受
- currentValue - 从数组中传递的当前元素。
- thisArg(可选)- 在执行 callback 时用作 this 的值。默认情况下,它是
undefined
。
map() 返回值
- 返回一个新数组,其中包含对每个元素调用
callback
函数的返回值。
注意事项:
map()
不会更改原始数组。map()
按顺序为每个数组元素执行callback
一次。map()
不为没有值的数组元素执行callback
。
示例 1:使用自定义函数映射数组元素
const prices = [1800, 2000, 3000, 5000, 500, 8000];
let newPrices = prices.map(Math.sqrt);
// [ 42.42640687119285, 44.721359549995796, 54.772255750516614,
// 70.71067811865476, 22.360679774997898, 89.44271909999159 ]
console.log(newPrices);
// custom arrow function
const string = "JavaScript";
const stringArr = string.split(''); // array with individual string character
let asciiArr = stringArr.map(x => x.charCodeAt(0));
// map() does not change the original array
console.log(stringArr); // ['J', 'a', 'v', 'a','S', 'c', 'r', 'i', 'p', 't']
console.log(asciiArr); // [ 74, 97, 118, 97, 83, 99, 114, 105, 112, 116 ]
输出
[ 42.42640687119285, 44.721359549995796, 54.772255750516614, 70.71067811865476, 22.360679774997898, 89.44271909999159 ] [ 'J', 'a', 'v', 'a', 'S', 'c', 'r', 'i', 'p', 't' ] [ 74, 97, 118, 97, 83, 99, 114, 105, 112, 116 ]
示例 2:数组中对象元素的 map()
const employees = [
{ name: "Adam", salary: 5000, bonus: 500, tax: 1000 },
{ name: "Noah", salary: 8000, bonus: 1500, tax: 2500 },
{ name: "Fabiano", salary: 1500, bonus: 500, tax: 200 },
{ name: "Alireza", salary: 4500, bonus: 1000, tax: 900 },
];
// calculate the net amount to be given to the employees
const calcAmt = (obj) => {
newObj = {};
newObj.name = obj.name;
newObj.netEarning = obj.salary + obj.bonus - obj.tax;
return newObj;
};
let newArr = employees.map(calcAmt);
console.log(newArr);
输出
[ { name: 'Adam', netEarning: 4500 }, { name: 'Noah', netEarning: 7000 }, { name: 'Fabiano', netEarning: 1800 }, { name: 'Alireza', netEarning: 4600 } ]
注意:如果 callback
函数返回 undefined
或没有返回值,map()
会为新数组分配 undefined
。
另请阅读