繁体   English   中英

在删除操作中,api始终会删除提供的任何用户名或密码的最后一个json对象?

[英]In delete operation the api always deletes the last json object for any username or password provided?

每当我检查邮递员中的删除操作时,总会删除数组的最后一个元素。 我希望删除特定元素。

码:

app.post('/delete-user', (req, res)=> {
    users.splice(users.indexOf({ username: req.body.username, password:req.body.password}, 1))

    res.send(users)
})

MDN

indexOf()使用严格相等===或三重等于运算符使用的相同方法indexOf()searchElement与Array的元素进行比较。

由于您使用的是对象数组,因此无法找到确切的对象,因为您正在创建一个新对象,而indexOf将始终返回-1

当在splice使用负索引时,它将从最后一个元素中删除。

您可以使用findIndex代替,这样您就可以比较对象属性并找到索引。

app.post('/delete-user', (req, res) => {
    const index = users.findIndex(u => u.username === req.body.username && u.password === req.body.password)
    if (index === -1) {
        res.status(404).send('Not Found')
        return
    }
    users.splice(index, 1)
    res.send(users)
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM