There are so many differences between for loop and forEach in JavaScript!

There are so many differences between for loop and forEach in JavaScript!

In normal work, there are several ways to loop through the array, but the most commonly used should be the for loop and the forEach method using the array.

Today, let's fully compare the difference between the two. Please watch it.

First, we define two arrays

const arr1 = ['apply','call','bind']
const arr2 = ['apply','call','bind']

Next, use different traversal methods to run different code blocks for comparison

1, Execute common code

for (let i = 0; i < arr1.length; i++) {
   console.log(arr1[i])
  }
arr2.forEach((item, index) => {
   console.log(item)
})

The printing results are the same

2, Modify the original array in the code

for (let i = 0; i < arr1.length; i++) {
   arr1[i] = arr1[i] + 1
}
console.log(arr1)
arr2.forEach((item, index) => {
   item = item + 1
})
console.log(arr2)

arr1 changes, arr2 does not

3, Using asynchronous functions in code

console.log(new Date())
 for (let i = 0; i < arr1.length; i++) {
  setTimeout(() => {
   console.log(arr1[i])
   console.log(new Date())
  }, 3000)
}
// arr2.forEach((item, index) => {
//  setTimeout(() => {
//   console.log(item)
//   console.log(new Date())
//  }, 3000)
// })
console.log(new Date())

First print the first console, then print the last console, and finally execute the intermediate command

4, Using await in code

function test() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve(new Date())
        }, 3000)
      })
    }
    async function fn() {
      for (let i = 0; i < arr1.length; i++) {
        console.log(await test())
      }
    }
    fn()

Print every three seconds

arr2.forEach(async (item, index) => {
   console.log(await test())
})

Print it out at the same time

5, break is included in the code

function test() {
   for (let i = 0; i < arr1.length; i++) {
​    console.log(arr1[i])
​    if (i === 1) {
​     break
​    }
   }
  }
  function test2() {
   arr2.forEach((item, index) => {
​    console.log(item)
​    // if (index === 1) {
​    //  break
​    // }
   })
  }
  test()
  test2()

If you don't comment it out, you will report an error

6, return is included in the code

 function test() {
  for (let i = 0; i < arr1.length; i++) {
​    console.log(arr1[i])
​    if (i === 1) {
​     return
​    }
   }
  }
  function test2() {
   arr2.forEach((item, index) => {
​    console.log(item)
​    if (index === 1) {
​     return
​    }
   })
  }
  test()
  test2()

When the test function executes, return terminates. When the test2 function executes, return does not terminate

Summary:

1. Use the for loop when processing the original array.

2. break cannot be used in foreach and return is not supported

3.for loop can realize interval printing, that is, forEach does not support asynchronous to synchronous

Essential difference:

The former is ergodic, and the latter is actually iterative

Traversal: refers to the regular and one-time access to each member of the data structure.

Iteration: iteration is a special form of recursion. It is a method provided by the iterator. By default, the members of the data structure are accessed one by one in a certain order.

<u> Special tips < / u >

For the array parameter operation of forEach callback function, the original array is changed

var array=[1,2,3];
array.forEach(function(value,index,data){
    ++value;
    data.push(value);
});
console.log(array,"array");
// [1, 2, 3, 2, 3, 4] "array"

So tomorrow, let's implement the forEach method and show you what iterators are

Keywords: Javascript

Added by YodaOfCamarilla on Fri, 28 Jan 2022 12:19:09 +0200