JavaScript语言,并且在循环,迭代和数组的主题范围内吗?另外,您偶然发现了这两种方法, Array.forEach() 并且Array.map()。最后,感到困惑吗?不用担心,因为在这篇文章中,我们将向您展示这两种方法之间的区别。
forEach和map的语法
什么是Array.forEach?
该forEach方法允许您为数组中的每个元素运行函数/方法。
//the syntax
[].forEach(function(item, index, array){
//do your stuff here...
});
论据 描述 需要
item 当前正在处理的项目 是
index 数组中当前项目的索引 没有
array 该数组forEach被调用 没有
快速范例
["apple", "mango", "avocado", "dragon fruit"].forEach(console.log);
论据 描述 需要
item 当前正在处理的项目 是
index 数组中当前项目的索引 没有
array 该数组forEach被调用 没有
如您所见,我们forEach通过传递console.log方法显示了方法的三个参数。很简单,不是吗?我们将在后面的部分中深入了解。
什么是Array.map?
该map方法返回一组新的数组,但不更改原始数组。
语法
//the syntax:
[].map(function(currentValue, index,currentArray){
//do your stuff here ...
}, thisValue)
论据 描述 需要
currentValue 当前正在处理的项目 是
index 数组中当前项目的索引 没有
currentArray 该数组map 被调用 没有
thisValue 执行回调时用作此值 没有
快速范例
["apple", "mango", "avocado", "dragon fruit"].map((currentValue) => currentValue.toUpperCase());
如您所见,我们已经展示了该map方法如何以大写形式返回一组新的数组。
forEach和map之间的区别
既然我们已经看到了这两种数组方法的语法,我们就可以回答它们的差异。将尽力解释使用代码示例的区别。但是,在进入每个细节之前,我们需要某种形式的数据。
const employees =
[{
employee: 'Eleanor R. Crane',
company: 'Tellus Faucibus Leo Incorporated',
dailyRate: 0,
salary: 15200
},
{
employee: 'Haviva E. Lane',
company: 'Eu Neque Pellentesque Incorporated',
dailyRate: 0,
salary: 13333
},
{
employee: 'Merrill F. Morrison',
company: 'Lobortis Quam Ltd',
dailyRate: 0,
salary: 1450
},
{
employee: 'Halee L. Hensley',
company: 'Elit Corp.',
dailyRate: 0,
salary: 15872
},
{
employee: 'Hamish T. Trevino',
company: 'Rhoncus LLC',
dailyRate: 0,
salary: 14214
}];
每次
没有结果值或不返回任何值
遍历一个列表,并对每个列表进行一些有副作用的操作。如果您需要做一些有意义的事情,可以在迭代时做一些副作用。
const TOTAL_WORKING_DAYS = 261;
//Horrible in my opinion, worst someone will say it is ugly.
const dailyRate = (item, index, array) => array[index].dailyRate =
Math.floor(((item.salary * 12) / (TOTAL_WORKING_DAYS)));
//undefined as forEach doesn't return any results.
let dailyRateEmployeeResults = employees.forEach(dailyRate);
console.log(dailyRateEmployeeResults); //undefined
console.log(employees); //With side effects
关于forEach方法的思考
每次使用该forEach方法时,我都观察到它描述了控制流程。没有神秘感,不是吗?因此,可以说这是当务之急。
地图
返回一个新列表,而不更改其他任何内容
没有副作用,它不会更改原始数组列表
const TOTAL_WORKING_DAYS = 261;
const getDailyRate = salary => Math.floor(((salary * 12) / (TOTAL_WORKING_DAYS)));
const dailyRate = employee => Object.assign({
},
{
employee: employee.employee, dailyRate: getDailyRate(employee.salary) });
//Returns a new set of employees with dailyRate and name
const newEmployees = employees.map(dailyRate);
//new data
console.log(newEmployees);
//old data
console.log(employees);
同样,回到我的观察,但是使用该map 方法,我已经观察到它有点像数据流。意思是,当您有一个输入数组时,它将通过使用此方法输出一个新数组。因此,可以说它是有功能的。