find方法的使用(处理简单数组,json数组)

113 阅读1分钟

概念

用于查找数组中符合条件的第一个元素,如果没有符合条件的元素,则返回undefined

注意:

对于空数组,函数是不会执行的;

不会改变数组的原始值;

语法:

array.find(function(currentValue, index, arr), thisValue)

参数: callback:必须。为数组中每个元素执行的函数,该函数接收三个参数==》

currentValue:必须。数组中正在处理的当前元素

index:可选。当前元素的索引值

arr:可选。当前元素所在的数组对象

thisValue:可选。传递给函数的值一般用"this"值。如果这个参数为空,"undefined"会传递给"this"值。

实例:

1. 求数组中第一个大于1的值
let arr = [1,2,3,4,5]
let num = arr.find(item => item > 1)
console.log(num) // 2

2. 提取第一个id为1的对象
let arr = [{
    id: 1,
    name: "张三",
    age: 25,
    class: "一级"
},{
    id: 2,
    name: "李四",
    age: 18,
    class: "三级"
}]
let obj = arr.find(item => item.id == 1)
console.log(obj) // {id:1, name:"张三", class:"三级"}

// 工作中使用:
getTime(flag) {
  if (flag == 0) {
    return this.visitRecordRequest.find(({ status }) => status == 0)
      .saveTime;
  } else if (flag == 1) {
    return this.visitRecordRequest.find(({ status }) => status == 1)
      .applyTime;
  } else if (flag == 2 || flag == 9) {
    return this.visitRecordRequest.find(
      ({ status }) => status == 2 || status == 9
    ).approveTime;
  } else if (flag == 3) {
    return this.visitRecordRequest.find(({ status }) => status == 3)
      .releaseTime;
  } else if (flag == 4 || flag == 6) {
    return this.visitRecordRequest.find(
      ({ status }) => status == 4 || status == 6
    ).signTime;
  } else if (flag == 7 || flag == 8) {
    return this.visitRecordRequest.find(
      ({ status }) => status == 7 || status == 8
    ).feedbackTime;
  } else if (flag == 5) {
    return this.visitRecordRequest.find(({ status }) => status == 5)
      .widthdrawTime;
  } else {
    return;
  }
}