This is the second day of my participation in the August More Text Challenge

A. To introduce the characteristics of javascript loop mode

1. The for loop

  • Use break to break the loop
  • Use continue to skip this iteration and continue with the next iteration
let arry = Array.from ({length:10},(v,i) = >i+1);
for (let i = 0; i < arry.length; i++) {
  console.log(arry[i])
}
Copy the code

2. The forEach loop

  • There is no way to break or skip a loop
let arry = Array.from ({length:10},(v,i) = >i+1);
arry.forEach((item, index) = > {
  console.log(item)
})
Copy the code

3. for… In circulation

  • Traverse object
  • Use break or continue to interrupt or skip
let obj={name:"aaa".age:"18"}
for (let key in obj) {
  console.log(key)
  console.log(obj[key])
}
Copy the code

4. for… Of circulation

  • Traversal arrays, strings, function parameters, Map, Set
  • Return the key
  • Use break or continue to interrupt or skip
let str = "abcdfrg"
for (const value of str) { 
  console.log(value);
}
Copy the code

5. New iteration method for ES6 array

  • Map, filter, reduce, every, some
5.1 Every () iterates through all items

If one element of the array fails, the entire expression returns false and the remaining elements are not checked

  • The default is return false, where return false is a break effect and return true is a continue effect
  • Does not recognize empty arrays []
  • It doesn’t change the original array
let arry = Array.from ({length:10},(v,i) = >i+1);
let newArr = arry.every((item,index) = >{
  return item == 1 
})
console.log(newArr) // false
Copy the code
5.2 Some () traversal meets the conditions of the option

If one of the array conditions is met, the expression returns true and the remaining elements are not checked

  • Does not recognize empty arrays []
  • It doesn’t change the original array
let arry = Array.from ({length:10},(v,i) = >i+1);
let newArr = arry.some((item,index) = >{
  return item == 1 
})
console.log(newArr) // true
Copy the code
5.3 Filter () Iterates through the desired options

Returns an array of items that match the criteria

  • Does not recognize empty arrays []
  • It doesn’t change the original array
let arry = Array.from ({length:10},(v,i) = >i+1);
let newArr = arry.filter((item,index) = >{
  return item > 5 
})
console.log(newArr) // [6, 7, 8, 9, 10]
Copy the code
5.4 Map () Traversal generates the desired array structure
  • Does not recognize empty arrays []
  • It doesn’t change the original array
let arry = Array.from ({length:10},(v,i) = >i+1);
let newArr = arry.map((item,index) = >{
    return {
       v:item
    } 
})
console.log(newArr)
Copy the code

two conclusion

If you want to do exit interrupts for loops, you should not use forEach, but use new ES6 methods for arrays, as well as the common find and findIndex methods