在使用数组时,有时你需要循环或迭代数组的值,以便输出或操作它们。
这些数组可以容纳任何数据类型,包括对象、数字、字符串和许多其他数据。
在这篇文章中,我们将看看如何使用JavaScriptforEach() 数组方法来循环浏览所有类型的数组,以及它与for循环方法的区别。
在JavaScript中,有许多迭代方法,包括forEach() 方法,它们几乎都执行相同的功能,只是略有不同。是否使用特定的循环方法完全取决于你,但重要的是,我们要了解每一种方法以及它们的工作原理。
JavaScript forEach()
forEach() 数组方法在任何数组中循环,对每个数组元素按升序索引顺序执行一次提供的函数。这个函数被称为回调函数。
注意:数组是元素的集合,可以是任何数据类型。
forEach()循环的语法和参数
下面是写forEach循环的标准方法。
array.forEach(callbackFunction);
array.forEach(callbackFunction, thisValue);
回调函数最多可以接受三个不同的参数,尽管不是所有的参数都需要。下面是一些forEach() 循环的例子,它们同时使用了普通函数和ES6方法来声明回调函数。
// Using only Current Element
array.forEach((currentElement) => { /* ... */ })
array.forEach(function(currentElement) { /* ... */ })
// Using only Current Element and Index
array.forEach((currentElement, index) => { /* ... */ })
array.forEach(function(currentElement, index) { /* ... */ })
// Using only Current Element, Index and array
array.forEach((currentElement, index, array) => { /* ... */ })
array.forEach(function(currentElement, index, array){ /* ... */ })
// Using all parameters with thisValue (value of this in the callback)
array.forEach((currentElement, index, array) => { /* ... */ }, thisValue)
array.forEach(function(currentElement, index, array) { /* ... */ }, thisValue)
上面的语法可能看起来很混乱,但这是编写forEach循环的一般语法,取决于你想使用的值。让我们回顾一下我们使用的所有参数。
callbackFunction:回调函数是一个对每个元素只执行一次的函数,可以接受以下参数,在回调函数中使用。
currentElement:当前元素,顾名思义,就是在循环发生时正在处理的数组中的元素。它是唯一必要的参数。index: index是一个可选的参数,它带有currentElement的索引。array:array是一个可选的参数,返回传递给forEach()方法的数组。
thisValue::这是一个可选的参数,用于指定在回调函数中使用的值。
总之,forEach() 数组迭代方法接受一个回调函数,该函数持有的参数可以在回调函数中用于每个数组项,如数组项,该项的index ,以及整个数组。
forEach()在JavaScript中的例子
在我们看其他可能的例子之前,让我们看看我们传入回调函数的所有参数以及它们可以用来做什么。
如何使用currentElement 参数
假设我们有一个员工详细信息的数组,包括他们的姓名、年龄、工资数额和货币。
const staffsDetails = [
{ name: "Jam Josh", age: 44, salary: 4000, currency: "USD" },
{ name: "Justina Kap", age: 34, salary: 3000, currency: "USD" },
{ name: "Chris Colt", age: 37, salary: 3700, currency: "USD" },
{ name: "Jane Doe", age: 24, salary: 4200, currency: "USD" }
];
如果我们想单独显示所有的名字,并在其周围加上一些文字,我们可以使用forEach() ,方法如下。
staffsDetails.forEach((staffDetail) => {
let sentence = `I am ${staffDetail.name} a staff of Royal Suites.`;
console.log(sentence);
});
输出。
"I am Jam Josh a staff of Royal Suites."
"I am Justina Kap a staff of Royal Suites."
"I am Chris Colt a staff of Royal Suites."
"I am Jane Doe a staff of Royal Suites."
注意:如果是一个包含键/值对的对象,我们也可以通过这种方式对currentElement 值进行解构。
staffsDetails.forEach(({ name }, index) => {
let sentence = `I am ${name} a staff of Royal Suites.`;
console.log(sentence);
});
如何使用index 参数
我们也可以只利用未建立的索引参数来获得每个数组项的index ,这种方式。
staffsDetails.forEach((staffDetail, index) => {
let sentence = `index ${index} : I am ${staffDetail.name} a staff of Royal Suites.`;
console.log(sentence);
});
输出。
"index 0 : I am Jam Josh a staff of Royal Suites."
"index 1 : I am Justina Kap a staff of Royal Suites."
"index 2 : I am Chris Colt a staff of Royal Suites."
"index 3 : I am Jane Doe a staff of Royal Suites."
如何使用array 参数
array 参数是第三个参数,它持有正在被迭代的原始数组。例如,我们可以尝试这样在我们的控制台显示数值。
staffsDetails.forEach((staffDetail, index, array) => {
console.log(array);
});
这将使整个数组输出4次,因为我们有4个项目,迭代运行4次。让我们对一个有几个值的数组进行操作,这样我就可以把输出加到这里。
let scores = [12, 55, 70];
scores.forEach((score, index, array) => {
console.log(array);
});
输出。
[12,55,70]
[12,55,70]
[12,55,70]
到目前为止,我们已经使用了回调函数的每个参数。让我们看一些其他的例子来充分了解它是如何工作的,然后再与for循环方法做一个快速比较。
如何将一个数字数组中的所有数值相加?forEach()
假设我们有一个scores 的数组。我们可以使用forEach() 数组方法来循环并帮助将这些数字相加。
const scores = [12, 55, 70, 47];
let total = 0;
scores.forEach((score) => {
total += score;
});
console.log(total);
回顾一下,早些时候,我们利用了一个员工详细信息的数组。现在让我们试着把所有工作人员的工资加在一起,看看它是如何与对象一起工作的。
let totalSalary = 0;
staffsDetails.forEach(({salary}) => {
totalSalary += salary;
});
console.log(totalSalary + " USD"); // "14900 USD"
注意:我们解构了currentElement's Object。
如何在forEach() 回调函数中使用条件语句
当在数组中循环时,我们可能想检查特定的条件,就像通常使用for循环方法那样。我们可以将这些条件传入我们的回调函数或任何其他我们想在每个数组项目上运行的操作。
例如,如果我们只想显示我们前面声明的工作人员详细信息数组中工资大于或等于4000 的人的名字,我们可以做如下操作。
staffsDetails.forEach(({name, salary}) => {
if(salary >= 4000){
console.log(name);
}
});
输出。
"Jam Josh"
"Jane Doe"
forEach()与for循环的比较
for循环与forEach方法非常相似,但两者都拥有一些独特的功能,如。
循环中的突破和继续
当在一个数组中进行循环时,我们可能想在满足某个条件时脱离或继续循环(意味着我们跳过)。这在break 和continue 指令中是可以实现的,但在forEach() 方法中却不能实现,如下图所示。
const scores = [12, 55, 70, 47];
scores.forEach((score) => {
console.log(score);
if (score === 70)
break;
});
这将抛出一个语法错误:Illegal break statement 。这也适用于continue指令,它也会抛出一个Illegal continue statement: no surrounding iteration statement 。
const scores = [12, 55, 70, 47];
scores.forEach((score) => {
if (score === 70)
continue;
console.log(score);
});
但幸运的是,这在for循环方法中完全有效。
const scores = [12, 55, 70, 47];
for (i = 0; i < scores.length; i++) {
console.log(scores[i]);
if (scores[i] === 70)
break;
}
输出。
12
55
70
continue 指令也是如此。
const scores = [12, 55, 70, 47];
for (i = 0; i < scores.length; i++) {
if (scores[i] === 70)
continue;
console.log(scores[i]);
}
输出。
12
55
47
有缺失元素的数组
另一个重要的比较是在这样的情况下,我们所迭代的数组有一些缺失的值/数组项,如下图所示。
const studentsScores = [70, , 12, 55, , 70, 47];
这可能是由于开发人员的错误或其他原因,但这两种方法采取了两种不同的方法来循环处理这些类型的数组。for循环在有缺失值的地方返回未定义值,而forEach() 方法则跳过它们。
For 循环
const studentsScores = [70, , 12, 55, , 70, 47];
for (i = 0; i < studentsScores.length; i++) {
console.log(studentsScores[i]);
}
输出。
70
undefined
12
55
undefined
70
47
forEach()
const studentsScores = [70, , 12, 55, , 70, 47];
studentsScores.forEach((stundentScore) => {
console.log(stundentScore);
});
输出。
70
12
55
70
47
注意:Async/Await对forEach() 数组方法不起作用,但对for循环方法起作用。
总结
在这篇文章中,我们学习了如何使用forEach() 数组方法,它允许我们循环浏览任何类型的项目的数组。它还允许我们写出比for循环更干净、更易读的代码。