Usage and difference of commonly used array traversal methods forEach, filter, some, every, map, find, reduce

-forEach is equivalent to for loop

let arr = [1,2,3,4,5]

let a = arr.forEach((val,index)=>{
    
    
    arr[index] +=1
    return index
})
console.log(a)   //undefined
console.log(arr)  // [2, 3, 4, 5, 6]

map

let arr = [1,2,3,4,5]

let arr1 = arr.map((val,index)=>{
    
    
    return arr[index] + 1
})
console.log(arr)   //[1,2,3,4,5]
console.log(arr1)  //[2, 3, 4, 5, 6]
  • The difference between map and forEach is that forEach has no return value, even if it returns, its return value will only be undefined;
  • All return values ​​of map will form a new array

some

let arr = [1,2,3,4,5]

let some1 = arr.some((val,index)=>{
    
    
    return val==1
})
console.log(some1)  //true

let some2 = arr.some((val,index)=>{
    
    
    return val==6
})
console.log(some2)  //false

find

let arr = [1,2,3,4,5]

let find1 = arr.find((val,index)=>{
    
    
    return val>1
})
console.log(find1)  // 2
  • The same: find and some have similar usages, both of which look for qualified values ​​in the array, and stop traversing backwards when a qualified value is found.
  • Difference: the value returned by some is a boolean, while the value returned by find is a specific value.

filter

let arr = [1,2,3,4,5]

let filter1 = arr.filter((val,index)=>{
    
    
    return val>1
})
console.log(filter1)   //[2,3,4,5]
  • Find the "all" values ​​that meet the conditions in the specified array and combine them into a new array without changing the original array

every

let arr = [1,2,3,4,5]

let every1 = arr.every((val,index)=>{
    
    
    return val>0
})
console.log(every1)   //true

let every2 = arr.every((val,index)=>{
    
    
    return val>1
})
console.log(every2)    //false
  • Judge whether "all" values ​​in the array meet the condition, return true if it meets, otherwise, false

reduce

let arr = [1,2,3,4,5]
let arrString = ["one","two","three","four","five"]
let sum1 = arr.reduce((item,val)=>{
    
    
    return item+val
})
let sum2 = arrString.reduce((item,val)=>{
    
    
    return item+val
})
console.log(sum1)  //15
console.log(sum2)  //onetwothreefourfive

  • If the array element is a number, the sum of all the elements in the array will be calculated; if the array element is a character, all the characters will be joined together

Guess you like

Origin blog.csdn.net/weixin_43956521/article/details/110951957