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