Help me understand how forEach works in js. There was a good illustrative example. One and the same problem solved using “for” and “forEach”
Thanks
I’ll format my question to make it clearer. Thanks for the answer to those who answered.
Because of what the question arose. I figured out how to rewrite this code using forEach
let length = 1;
snake = [];
for (let i = length - 1; i & gt; = 0; i--) {
}
And it turned out to be not as easy as I thought. That is why I need a visual example with forEach and for to understand how it works. I would be grateful
Answer 1, authority 100%
The forEach ()
method executes the specified function once for each element in the array.
arr.forEach (callback [ thisArg])
callback -
The function that creates an element of the new array takes three arguments:
currentValue
The current element being processed in the array.
index
The index of the currently processed element in the array.
array
The array to traverse.
thisArg
Optional parameter. The value to use as this
when calling the callback
function.
The forEach ()
method executes the callback
function once for each element in the array in ascending order. It will not be called for deleted or missing array elements. However, it will be called for elements that are present in the array and have the value undefined
.
The callback
function will be called with three arguments:
element value (value
)
element index (index
)
array to traverse (array
)
If the thisArg
parameter was passed to the forEach ()
method, it will be used as the this
value when the callback
is called. Otherwise, undefined
will be used as the this
value. Ultimately, the this
value seen from the callback
function is determined according to the usual rules for defining this
as seen from the function.
The range of elements processed by the forEach ()
method is set before the first call to the callback
function. Items added to the array after the forEach ()
method starts executing will not be visited by the callback
function. If the existing array elements change, the values passed to the callback
function will be the values at the time the forEach ()
method visits them; deleted items will not be visited.
function logArrayElements (element, index, array) {
console.log ('a [' + index + '] =' + element);
}
// Note the skip at index 2, there is no element, so it is not visited
[2, 5, 9] .forEach (logArrayElements);
// logs:
// a [0] = 2
// a [1] = 5
// a [3] = 9
Answer 2, authority 50%
ForEach takes an iterator function, the iterator function is called for each entry in the array.
var a = ["a", "b", "c"];
a.forEach (function (entry) {
console.log (entry);
});