Home > Article > Web Front-end > How to execute specified function on elements in js array
In the previous article, we learned about how to fill an array with fixed values. Please see "How to fill an array with fixed elements in js". This time we will learn about the method of executing specified functions on elements. You can refer to it if necessary.
First let’s look at a small example.
<script> var arr = new Array(7); arr[0] = "one"; arr[1] = "two"; arr[2] = "three"; arr.forEach(element => console.log(element)); </script>
The result of this small example is
Looking at this result carefully, we can find that this result is the elements existing in the array All are output. Let’s take a look at this code again. “console.log” is used in this code, and we also use the forEach method. Let’s take a look at it in detail.
The forEach() method executes the given function once for each element of the array.
Let’s take a look at the syntax format of this method.
数组名称.forEach(数组中每个元素执行的函数(正在处理的当前元素,正在处理的当前元素的索引,正在操作的数组), 执行回调函数时,用作this的值)
The forEach() method executes the callback function once for each item in the array that contains a valid value in ascending order. Those items that have been deleted or uninitialized will be skipped (for example, on a sparse array). This method executes the callback function once for each array element; unlike map() or reduce(), it always returns an undefined value and cannot be chained. A typical use case is to perform side effects at the end of a call chain.
When forEach() is called, it will not change the original array, that is, the array it is called from (although the callback function may change the original array when it is called).
Note: There is no way to abort or break out of the forEach() loop other than throwing an exception. If you need to abort or break out of a loop, the forEach() method is not the tool to use.
If you need to terminate the loop early, you can use:
A simple for loop
for...of / for... in loop
Array.prototype.every()
Array.prototype.some()
Array.prototype.find()
Array.prototype.findIndex()
That’s all, if you need it, you can See: javascript basic tutorial
The above is the detailed content of How to execute specified function on elements in js array. For more information, please follow other related articles on the PHP Chinese website!