javascript - 通过 findIndex 方法比较 'id'

标签 javascript arrays reactjs object ecmascript-6

如果在数组中找不到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)
}

最佳答案

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

console.log(!!-1);

所以你应该根据你的条件检查-1:

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

关于javascript - 通过 findIndex 方法比较 'id',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57342889/

相关文章:

c - 展开一个非指针数组

python - 使用不同长度的数组列表索引一维数组

reactjs - React useEffect 和 setInterval

node.js - 如何仅在提交更改后而不是更改期间提交更新的照片?

javascript - 如何自动聚焦于 React 中的特定输入字段(单击另一个元素后)?

javascript - 使用 Google map 绘制巴士路线

javascript - RTCSessionDescription 和视频/音频广播

javascript - 如何防止两个 div 在我的网页首次加载时跳来跳去?

javascript - 在 Linux 上部署 Javascript 应用程序的最简单方法

c - 在 C 中将二维整数数组值全部设置为 0