JavaScript数组map()
目录
JavaScript Array 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 amout 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
分配给新数组。
推荐读物: JavaScript Array filter()
上一篇: JavaScript数组长度
下一篇: ()的JavaScript数组
总计 0 评论