More detailed array traversal methods in here js traversal number group chapter (two) – traversal number group of various methods

ForEach changes the original data

let arr = [1.2.3.4.5]

// Invalid modification
arr.forEach(num= > {
  num = 123
})
console.log(arr); // [1, 2, 3, 4, 5]

// Valid modification
arr.forEach((num, index) = > {
  arr[index] = 123
})
console.log(arr); // [123, 123, 123, 123, 123]
Copy the code

In forEach, num is passed by value, so changing num does not affect arr[index].

ForEach implements continue/break

ForEach method can’t terminate traversal. You can’t use a continue/break function directly (because forEach is passing a callback that doesn’t have a continue/break function and returns it).

let arr = [1.2.3.4.5]

Implement the continue effect
arr.forEach(num= > {
  if (num === 3) return   
  console.log(num); // 1 2 4 5
})

// Break (for loop)
let isBreak = false
arr.forEach(num= > {
  if (isBreak) return
  if (num === 3) {
    isBreak = true
    return
  }
  console.log(num); / / 1. 2
})
Copy the code

The forEach map/set

let set = new Set(['a'.'b'.'c'.'d'.'e'])
set.forEach((value, key) = > { // Set key and value are the same
  console.log('key:' + key + ' ' + 'value:' + value);
})
// key:a value:a
// key:b value:b
// key:c value:c
// key:d value:d
// key:e value:e

let arr2 = [ [1.'a'], [2.'b'], [3.'c'], [4.'d'], [5.'e']]let map = new Map(arr2) 
console.log(map);
map.forEach((value, key) = > { // forEach value before key
  console.log('key:' + key + ' ' + 'value:' + value);
})
// Map(5) { 1 => 'a', 2 => 'b', 3 => 'c', 4 => 'd', 5 => 'e' }
// key:1 value:a
// key:2 value:b
// key:3 value:c
// key:4 value:d
// key:5 value:e
Copy the code

Comparison of forEach and Map methods

let res = arr.forEach(num= > ++num)
console.log(arr); // [1, 2, 3, 4, 5]
console.log(res); // undefined

let res2 = arr.map(num= > ++num)
console.log(arr); // [1, 2, 3, 4, 5]
console.log(res2); // [2, 3, 4, 5, 6]
Copy the code
forEach map
Returns the undefined Returns a new array after processing
The same
The original array will not be changed
They all have parameters item,index,arr