简体   繁体   English

查找字符串数组中是否已经存在字符串-javascript

[英]Finding if a string already exists inside an array of strings -javascript

I have an array called blog.likes and i want to check to see if the id of the current logged in user(req.user._id) already exists inside the array of likes. 我有一个名为blog.likes的数组,我想检查一下当前已登录用户(req.user._id)的ID是否已存在于点赞数组中。 If it does then delete the id from the array if it doesn't then add the user id inside the array. 如果确实存在,则从阵列中删除ID;如果没有,则在阵列中添加用户ID。 With the code i have now if i press the like button once it likes the post if i press it again it removes the like but if a post has a like and i log in with a different user and press the like button many times it starts to delete all the likes not only the likes that are made by one user. 使用现在的代码,如果我按一次赞按钮,如果我再按一次赞按钮,则它会删除赞,但是如果帖子中有一个赞,并且我以其他用户身份登录并多次按赞按钮,它将启动赞删除所有赞,而不仅仅是删除一个用户的赞。

         if (blog.likes.indexOf(req.user._id) > -1 ){
             blog.likes.shift(req.user._id);
             blog.save();
           } else {
          blog.likes.push(req.user);
           blog.save();
          }

The shift function will only remove the first element from the array, paying no heed to the logged in user id. shift函数只会从数组中删除第一个元素,而无需注意已登录的用户ID。 Use splice function to achieve the desired result. 使用拼接功能可获得所需的结果。 Change your code to this: 将代码更改为此:

let userIndex = blog.likes.indexOf(req.user._id);
if (userIndex > -1) {
  blog.likes.splice(userIndex, 1);
} else {
  blog.likes.push(req.user);
}
blog.save();

As I mentioned in the comments .shift() is not the correct method to use. 正如我在评论中提到的那样,.shift()不是正确的方法。 Give this a try: 试试看:

var f = blog.likes.indexOf(req.user._id);
if (f > -1 ) {
  blog.likes.splice(f, 1);
} else {
  blog.likes.push(req.user);
}
blog.save();

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

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