JavaScript arr.map
时间: 2023-06-30 21:17:45 浏览: 99
JavaScript 中的 Array.map()
方法是用于对数组中的每个元素进行操作,并返回一个新的数组。它接收一个函数作为参数,该函数接收三个参数:当前元素的值、该元素的索引和数组本身。在该函数中,你可以对当前元素进行操作并返回一个新的值,最终这些值会组成一个新的数组返回。原始数组不会被修改。
例如,下面的代码演示了如何将数组中的每个元素都加上 1 并返回一个新的数组:
const arr = [1, 2, 3, 4, 5];
const newArr = arr.map((value, index, array) => {
return value + 1;
});
console.log(newArr); // 输出 [2, 3, 4, 5, 6]
在这个例子中,我们使用 Array.map()
方法将数组中的每个元素都加上 1 并返回一个新的数组。
值得注意的是,Array.map()
方法返回的是一个新的数组,而不会修改原始数组。因此,如果你需要对原始数组进行修改,应该使用 Array.forEach()
或 Array.reduce()
等其他方法。
相关问题
javascript arr.map
JavaScript中的Array.map()
方法是用于对数组中的每个元素执行指定的操作,并返回一个新的数组,新数组的元素是原始数组元素经过操作后的结果。
Array.map()
方法的语法如下:
array.map(function(currentValue, index, arr), thisValue)
参数说明:
function(currentValue, index, arr)
:必需。函数,数组中的每个元素都会执行这个函数。该函数有三个参数:currentValue
:必须。当前元素的值。index
:可选。当前元素的索引。arr
:可选。当前元素所属的数组对象。
thisValue
:可选。对象作为该执行回调时的this
对象。
示例:
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = numbers.map(function(num) {
return num * 2;
});
console.log(doubleNumbers); // [2, 4, 6, 8, 10]
上面的示例中,我们通过Array.map()
方法将原始数组numbers
中的每个元素都乘以2,返回一个新的数组doubleNumbers
。
const arr = [ { name: 'ceshi1', value1: 345, value2: 85934 }, { name: 'ceshi2', value1: 3432, value2: 343432 }, ]; const result = Math.max( ...arr.map(obj => obj.value1), ...arr.map(obj => obj.value2) );找到最大值的那个字段
可以使用 reduce()
方法来实现:
const arr = [
{ name: 'ceshi1', value1: 345, value2: 85934 },
{ name: 'ceshi2', value1: 3432, value2: 343432 },
];
const result = arr.reduce((max, obj) => {
const objMax = Math.max(obj.value1, obj.value2);
return objMax > max.value ? { value: objMax, name: obj.name } : max;
}, { value: -Infinity });
console.log(result.name); // 输出 ceshi2
这段代码会遍历 arr
数组中的每个对象,计算出它们的 value1
和 value2
字段的最大值,然后将结果与已知的最大值进行比较,返回一个新的最大值对象,直到遍历完所有的对象。最终得到的 result
对象就是拥有最大值的那个对象,它的 name
字段即为所求的结果。
相关推荐
















