To loop through an array in JavaScript, you can use the forEach()
method. The forEach()
method executes a provided function once for each array element.
Here's an example of how to use forEach()
:
index.tsx106 chars6 lines
This will output:
index.tsx20 chars4 lines
In the callback function, element
represents the current element being processed in the loop. You can also include two additional parameters: index
, which represents the index of the current element being processed, and array
, which is the array that forEach()
is being applied to.
index.tsx127 chars6 lines
This will output:
index.tsx26 chars4 lines
Note that the forEach()
method is not supported in Internet Explorer 8 or earlier versions, so you may need to use a different method or a polyfill if you need to support older browsers.
gistlibby LogSnag