如何验证我的数组中是否存在某个值?

How can I verify if a certain value exists in my array?

我正在从数据库(MongoDB 使用 Mongoose)中获取“评论”列表,每个评论都包含一组可以查看这些评论的允许用户。如何验证登录的用户是否在该数组中?

      <% if(comment.allowed.length  > 0 ){  %>
         <% for(i = 0 ; i < comment.allowed.length; i++) { %>
             <% if(comment.allowed[i] === auth) {  %>
                    You already payed
             <%  } else { %>
                    <form action="/pay" method="POST">
                         <button class="button-upload">Pay </button>
                    </form>                                     
             <% } %>
         <% } else {  %>
                    <form action="/pay" method="POST">
                         <button class="button-upload">Pay </button>
                    </form>
          <% } %>
       <% } %>

我已经这样做了,但是在我的数组中我收到了 2 封电子邮件:email1@mail.com 和 email2@mail.com。 登录的用户是 email1@mail.com,在我的页面中,我得到了“您已经付款”和带有按钮的表单,因为第一个值为 true,然后第二个值为 false。在我呈现页面的 .js 文件中,我可以使用 array.includes(value),但在这里我不能。我怎样才能只显示其中一个案例?还有许多其他评论,对于每一个我都必须验证这一点,这就是为什么我没有在我的 .js 文件中这样做,我会忘记登录用户可以看到或看不到的评论。

是否有我可以在我的 EJS 文件中使用的 array.includes(value) 的等价物,或任何解决方案来完成我想要的? 提前致谢!

这比 mongodb 更像是一个 javascript 数组问题。

有很多方法可以解决这个问题,我将提及其中的一些。

解决此问题的常规方法是遍历数组并检查值是否是您要查找的值(登录用户)。

假设您的允许用户数组是

let arr = ["bob@bob.com", "divine@gmail.com", "email1@mail.com", "email2@mail.com"]

您当前登录的用户是 email1@mail.com,

解决方案 1(Array.find):

const loggedInUser = "email2@mail.com"
const result = arr.find(value => value === loggedInUser) // This is going to 
// return "undefined" if loggedInUser is not in the array of allowed users.

if(result){
   // Do something
}

您的模板应如下所示

<% if(comment.allowed.length  > 0 ){  %>
       <% if(comment.allowed.find(value => value === auth)) {  %>
              You already payed
       <%  } else { %>
              <form action="/pay" method="POST">
                   <button class="button-upload">Pay </button>
              </form>                                     
       <% } %>
<% } %>

检查数组中是否存在某些内容的其他几种方法是:

const result = arr.indexOf(loggedInUser) // Array.indexOf -- Check if the value is not less than zero

const result = arr.filter(v => v === loggedInUser).join(' ') // Array.filter -- Returns the "loggedInUser" value

const result = arr.includes(loggedInUser) // Array.includes -- Returns a boolean