JavaScript forEach Array(js forEach遍历数组)

2,101 阅读3分钟

JavaScript forEach Array

JavaScript forEach遍历数组简介

JavaScript forEach数组用于在JavaScript中迭代一个数组。forEach方法以升序迭代而不修改数组。JavaScript forEach方法只对数组起作用。如果一个数组中没有元素,forEach方法不会被执行。如果数组中已有的元素被改变或删除,传递给回调的值将是为forEach方法传递的值。让我们看看JavaScript forEach方法是如何工作的,它的语法和一些插图可以让你更好地理解。

语法

sampleArray.forEach(function, (currentValue, index, array), thisValue);

在这里,参数的描述如下。

  • **sampleArray。**它是用于调用forEach方法的数组。
  • **forEach。**它是在一个带有其他参数的数组上调用的方法。
  • **function, (currentValue, index, array):**需要用3个参数的函数来运行数组中的每个元素
    • currentValue。这是当前元素的值。
    • index。这是要处理的元素的索引。
    • array: 数组。这是要调用函数的数组对象。
  • **thisValue:**这是函数执行时用作 "this "的值。如果没有提供'this'值,就会传递'undefined'。

这里,index、array和thisValue是可选参数。

JavaScript forEach数组的例子

我们将通过例子来看看forEach方法在实际编程中是如何使用的。

例一

代码

<!DOCTYPE html>
<html>
<body>
<p>Listing all the array items using forEach method</p>
<p id="demo"></p>
<script>
var veggies = ["Potato", "Spinach", "Capsicum"];
veggies.forEach(sampleFunc);
function sampleFunc(itemName, index) {
document.getElementById("demo").innerHTML += index + ":" + itemName + "<br>";
}
</script>
</body>
</html>

输出

JavaScript forEach Array output 1

例二

代码

<!DOCTYPE html>
<html>
<body>
<p>Multiplication of each array item with itself by iterating the array using forEach</p>
<p id="demo"></p>
<script>
const numbers = [23, 3, 43, 4, 78, 8];
const square = [];
numbers.forEach(function(num){
square.push(num*num);
});
document.write(square);
</script>
</body>
</html>

输出

JavaScript forEach Array output 2

例三

代码

<!DOCTYPE html>
<html>
<body>
<p>Accessing the index item for each element in array using forEach method</p>
<p id="demo"></p>
<script>
const employeeNames = ['Karthick', 'Jack', 'June'];
function iterateFunc(item, index) {
document.write(`${item} has index ${index}` + "<br/>");
}
employeeNames.forEach(iterateFunc);
</script>
</body>
</html>

输出

JavaScript forEach Array output 3

例四

forEach()方法接受一个同步函数,不等待承诺。

代码

<!DOCTYPE html>
<html>
<body>
<p>Addition of two numbers by iterating array using forEach method</p>
<p id="demo"></p>
<script>
let numbers = [50, 14, 25];
let sumNum = 0;
let sumFunction = async function (a, b, c)
{
return a + b + c
}
numbers.forEach(async function(x) {
sumNum = await sumFunction(sumNum, x)
})
document.write(sumNum)
</script>
</body>
</html>

输出

output 4

forEach()方法为每个数组元素依次调用所提供的函数,并使用项目来存储当前值,数组中所有元素的结果都显示在控制台。

例五

代码

<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method to find the index of the item</p>
<p id="demo"></p>
<script>
var array = ["Karthick","Sandeep","Honey","Jack"];
array.forEach(function(item,index,arr) {
document.write("item: " + item + " at index: " + index + " in the array: " + arr + " <br/> ");
})
</script>
</body>
</html>

输出

output 5

我们已经看到这个forEach()方法是如何使用的,同时也应该知道何时要使用forEach():

  • forEach()是用来遍历数组项目的,没有任何副作用。
  • 一些副作用是外部范围变量、DOM操作、I/O操作等。
  • 在回调函数中,输入字段的值被清除了。
  • 通常情况下,forEach()的迭代不能被打破,为了打破这个链条,我们需要使用一些其他的数组方法,比如array.map(), array.every(), array.some()或者array.reduce()。

例六

代码

<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method to detect if all numbers in array are even</p>
<p id="demo"></p>
<script>
let allEven = true;
const numbers = [22, 32, 42, 10];
numbers.forEach(function(number) {
if (number % 2 === 1) {
allEven = false;
}
});
document.write(allEven);
</script>
</body>
</html>

输出

output 6

上面这段代码确定了数组中的所有数字是偶数还是诺数,并给出了布尔值 "true "或 "false"。如果我们想在数组[4, 7, 9,6]的奇数7处中断forEach(),可以使用array.every(),这样在找到奇数后立即中断迭代,而不是迭代整个数组后再给出结果。

例七

代码

<!DOCTYPE html>
<html>
<body>
<p>Using forEach() method for programming a Counter</p>
<p id="demo"></p>
<script>
function sampleCounter() {
this.count = 0;
let num = this;
return {
increase: function () {
num.count++;
},
current: function () {
return num.count;
},
reset: function () {
num.count = 0;
}
}
}
var counter = new sampleCounter();
var numbers = [5, 3, 8];
var sumNum = 0;
numbers.forEach(function (e) {
sumNum += e;
this.increase();
}, counter);
document.write("Sum of numbers in array is: ", sumNum + "<br/>");
document.write("counter value: " , counter.current());
</script>
</body>
</html>

输出

output 7

这里我们创建了一个新的对象sampleCounter并定义了一个3个数字的数组。声明一个变量sumNum并赋值为0。然后我们在数组中调用forEach()方法,并将其添加到对象中,增加()方法。因此,最终的输出将是数组的总和和数组中的元素的数量。

总结

至此,我们结束了 "JavaScript forEach()数组在不破坏或不涉及任何副作用的情况下执行或迭代一个数组 "的主题。我们已经看到了什么是Array中的JavaScript forEach()方法以及它的语法。通过上面列出的一些简单的例子,你可以很容易地理解并进一步探索forEach()方法。我们也看到了使用forEach()编程时的一些限制。Array.forEach()方法是对数组项目进行迭代的有效方法之一。