3 different ways to loop through arrays in JavaScript in 2023

There are at least 3 different ways to loop over arrays in JavaScript. The three we will go over in this article are the

  1. forEach
  2. for of
  3. for loop

Using forEach to loop through an array

The forEach takes a callback function that is executed for element of the array. The callback function’s first argument is the element of the array.

const myArray = ["First", "Second", "Third"]

myArray.forEach(function(myElement, index, array) {
  console.log(`My Element is ${myElement}, index is ${index}, and array is {$array}`
}

Couple things to note about forEach

  1. You can not break out of the loop, it has to go through every element in the array.
  2. It is a higher order function
  3. The first argument is the array element, the second is the index, and the 3rd is the array itself

Using for of to loop through an array

Using the for of loop, we can loop through the array with

const myArray = ["First", "Second", "Third"]

for (const [i, myElement] of myArray) {
  console.log(`My Element is ${myElement}, index is ${i}`)
}

Looping through an array with a for loop

And using just a simple for loop, we can do

const myArray = ["First", "Second", "Third"]

for (let i = 0; i < myArray.length; i++) {
  console.log(`My Element is ${myarray[i]}, index is ${i}`)
}

https://stackoverflow.com/questions/50844095/should-one-use-for-of-or-foreach-when-iterating-through-an-array

Move multiple VLANs between two interfaces – Mikrotik

Move VLANs with foreach

Move all the VLANs under ether7 to ether6. Instead of an “=” sign, you can use a “~” to do a partial match.

foreach i in=[/interface vlan find where interface="ether7"] do={interface vlan set interface=ether6-master-local  $i } 

Move IP address to new port programmatically

Move ip address from ether6 to ether7. Change 192.168.88.1/24 to the address and the find command will find it regardless of the port and assign it to ether6 or whichever port is specified.

ip address set interface=ether6-master-local [find address="192.168.88.1/24"]

Using Delay

You can add a delay before a command runs by specifying delay and then the time to wait.

delay 60 

Use the ; to separate commands. Example below, wait 5 seconds then print the ip addresses.

delay 5 ; ip address print

Putting it all together

The following command/s will wait 60 seconds then move all the VLANs on ether7 to ether6 and then move the 192.168.88.1/24 address to ether6.

delay 60 ; foreach i in=[/interface vlan find where interface="ether7"] do={interface vlan set interface=ether6-master-local  $i } ; ip address set interface=ether6-master-local [find address="192.168.88.1/24"]