'What to do if i want to show the first 5 elements from the array by using forEach loop?
There are 10 elements in an array. What to do if i want to show the first 5 elements from the array by using forEach loop?
let arrays =[1, 2, 4, 6, 7, 44, 5, 7, 6]
arrays.forEach(array =>{}) //
Solution 1:[1]
To show the first 5 elements from the array by using forEach loop, you can use if statement
const arrays = [1, 2, 4, 6, 7, 44, 5, 7, 6];
arrays.forEach(function(value, index, array) {
if(index <= 4) {
document.write(value + "<br>");
}
});
Where parameters:
- Index = The index of the current element.
- Value = The value of the current element.
- Array = The array of the current element.
https://www.w3schools.com/jsref/jsref_foreach.asp https://www.w3schools.com/js/js_if_else.asp
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ferdy Setia |
