js determines whether an element exists in an array

Method 1: Use indexOf

  • If it does not exist, it returns -1. If it exists, it returns the index of the first occurrence.
let arr = [1, 2, 3, 4, 5, 6, 7, 8]

if (arr.indexOf(6) == -1) {
    
    
  console.log('不存在')
} else {
    
    
  console.log('存在,索引:', arr.indexOf(6))
}

Method 2: Use find

  • Its parameter is a callback function. All array elements traverse the callback function in sequence until the first element with a return value of true is found, and then return the element, otherwise undefined is returned.
let arr = [1, 2, 3, 4, 5, 6, 7, 8]

arr.find(item, index, (arr) => {
    
    
  if (item == 6) {
    
    
    console.log('索引:', index)
  }
})

Method 3: Use some

  • The some method is also used to detect whether there is an element that meets the condition. If there is, it will not continue to retrieve the following elements and return true directly. If it does not meet the conditions, it will return a false
let arr = [1, 2, 3, 4, 5, 6, 7, 8]

let result = arr.some((item) => item === 6)

console.log(result) //true

Method dead: use includes

  • ES6’s new array method is used to detect whether the array contains an element. If it does, it returns true, otherwise it returns false. What’s more powerful is that it can directly detect NaN
let arr = [1, 2, 3, 4, 5, 6, 7, 8NaN]

let flag = arr.includes(100)
let flag1 = arr.includes(NaN)

console.log(flag, flag1) // false true

Guess you like

Origin blog.csdn.net/yuan0209/article/details/128038217