The usage scenarios of findIndex method in JS and the difference with find

  1. typedArray.find: Returns the element to be found if found, returns undefined if not found
  2. typedArray.findIndex() is a built-in function in JavaScript. If the value satisfies the condition given in the function, the function is used to return the index in tyedArray, otherwise it returns -1
typedarray.findIndex(callback)

Parameters: It takes a parameter "callback" function which checks each element of the typedArray for which the provided condition is satisfied. The callback function takes three parameters as specified below:

  • element: It is the value of the element.
  • index: It is the index of the element.
  • array: An array is traversed.

Return Value: Returns the index in the array if the element satisfies the condition provided by the function; otherwise, returns -1.

findIndex example:

//示例1

const arr = [1, 2, 3, 4, 5, 3, 3, 2, 4, 5 ]
 
// 写法1
 
const index = arr.findIndex(item => {
    return item > 2
})
 
console.log(index) // 2
 
// 写法2
 
const index = arr.findIndex(item => item > 2)
 
console.log(index) // 2


--------------------------------------------------------------------

//示例2

const findArr = [
    { name: '张三', no: '15' },
    { name: '李四', no: '10' },
    { name: '王五', no: '5' }
  ]

  const fIndex = findArr.findIndex(({ name }) => name === '张三')

  console.log(fIndex) // 0

  const ffIndex = findArr.findIndex(({ name }) => name === '小付')

  console.log(ffIndex);// -1

find example:

//示例1

    const arr = [
      {
        name: '张三',
        age: 18
      },
      {
        name: '李四',
        age: 20
      },
      {
        name: '王五',
        age: 22
      }
    ]
 
    const val = arr.find(item => {
      return item.age === 20
    })
    
    //换种写法
    const val = arr.find(item => item.age === 20)
    console.log(val)  
     // {
            name: '李四',
            age: 20
        }


--------------------------------------------------------------------

//示例2

const findArr = [
    { name: '张三', no: '15' },
    { name: '李四', no: '10' },
    { name: '王五', no: '5' }
  ]

  const ffind = findArr.find(({ name }) => name === '张三')
 
  console.log(ffind) // { name: '张三', no: '15' }


  const fffind = findArr.find(({ name }) => name === '小付')

  console.log(fffind);// undefined

Practical application scenarios: such as looking up the ID to change the selected state, etc.

  <view class="todo-list" :class="{ 'todo--finish': item.checked }"
 v-for="(item, index) in listData" :key="index" @click="finish(item.id)">
    //点击列表表示已完成
    finish (id) {
      let index = this.list.findIndex((item) => item.id === id)
      this.list[index].checked = !this.list[index].checked
    },

 

Guess you like

Origin blog.csdn.net/ONLYSRY/article/details/128127428