【问题标题】:Comparing 'id' via the findIndex method通过 findIndex 方法比较“id”
【发布时间】:2019-12-12 01:12:22
【问题描述】:

如果在数组中找不到todo 对象的todos。将todo 添加到todos 数组。如果找到,请不要添加到板上。 比较表是否与给定的索引一起做。返回 -1 或 false。我的条件是if (! findObject) {} 应该将对象添加到数组而不是添加它

此处代码:https://stackblitz.com/edit/react-7wlg5m

const todos = [
  {
    "userId": 1,
    "id": 1,
    "title": "delectus aut autem",
    "completed": false
  },
  {
    "userId": 1,
    "id": 2,
    "title": "quis ut nam facilis et officia qui",
    "completed": false
  },
  {
    "userId": 1,
    "id": 5,
    "title": "fugiat veniam minus",
    "completed": false
  }
]

const todo = {
  "userId": 1,
  "id": 3,
  "title": "delectus aut autem",
  "completed": false
}

  let findObject = todos.findIndex(x => x.id === todo.id);
  console.log(findObject);

if(!findObject) {
  let newArray = [...todos];

  newArray.push(todo)
  console.log(newArray)
}

【问题讨论】:

    标签: javascript arrays reactjs object ecmascript-6


    【解决方案1】:

    如果找不到该项目,findIndex 将返回 -1,不幸的是,这不是一个虚假值 - 唯一的虚假数字值为 0。所有其他值 - 包括 -1 - 都是真实的。

    console.log(!!-1);

    所以你应该在你的情况下检查-1

    if (findObject == -1) {
      // ...
    }
    

    【讨论】:

      【解决方案2】:

      Jack Bashford 的答案的替代方法是使用 .find 而不是 .findIndex
      如果在 todos 数组中找不到 todo 并且 undefined 是一个假值,.find 将返回 undefined .

      Array.prototype.find() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

      
      let findObject = todos.find(x => x.id === todo.id);
      console.log(findObject);
      
      if(!findObject) {
        let newArray = [...todos];
      
        newArray.push(todo)
        console.log(newArray)
      }
      

      工作示例:https://repl.it/repls/TemporalLividCodegeneration

      【讨论】:

        【解决方案3】:

        您也可以使用 filter 方法来过滤掉匹配的 id。你可以这样做:

        let findObject = todos.filter(x => x.id === todo.id);
        console.log(findObject);
        
        if (!findObject.includes(todo.id)) {  
          let newArray = [...todos];
          newArray.push(todo);
          console.log(newArray);
        }
        

        您可以从这里了解更多关于过滤方法的信息:[https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter]

        希望这会有所帮助?

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-08-13
          • 2020-06-12
          • 1970-01-01
          • 2022-06-10
          • 1970-01-01
          相关资源
          最近更新 更多