Javascript 为什么我的$.inArray()函数在投票系统中不起作用?

Javascript 为什么我的$.inArray()函数在投票系统中不起作用?,javascript,jquery,mongodb,meteor,Javascript,Jquery,Mongodb,Meteor,我想允许用户只向上投票/向下投票一次,所以我想检查用户是否已经投票。但问题是,我的函数总是说用户已经投票了,MongoDB中的投票数组中没有单个用户ID。以下是函数: Template.postItem.events({ 'click': function() { Session.set("selected_post", this._id); }, 'click a.yes': function(event) { if (Meteor.u

我想允许用户只向上投票/向下投票一次,所以我想检查用户是否已经投票。但问题是,我的函数总是说用户已经投票了,MongoDB中的投票数组中没有单个用户ID。以下是函数:

Template.postItem.events({
    'click': function() {
        Session.set("selected_post", this._id);
    },

    'click a.yes': function(event) {
        if (Meteor.user()) {
            event.preventDefault();
            if ($.inArray(Meteor.userId(), Posts.voted)) {
                console.log('User already voted.');
            } else {
                var postId = Session.get('selected_post');
                console.log("voting" + Meteor.userId());
                Posts.update(postId, {$push: {voted: Meteor.userId()}});
                Posts.update(postId, {$inc: {'score' : 1}});
                }
            }
        }, 

inaray
是一个非常命名不好的函数:它返回找到该对象的索引,如果没有找到,则返回-1,(顾名思义)
true
如果找到,则返回
false
。所以你想要

if ($.inArray(Meteor.userId(), Posts.voted) !== -1) {
// ----------------------------------------^^^^^^^

inaray
是一个非常命名不好的函数:它返回找到该对象的索引,如果没有找到,则返回-1,(顾名思义)
true
如果找到,则返回
false
。所以你想要

if ($.inArray(Meteor.userId(), Posts.voted) !== -1) {
// ----------------------------------------^^^^^^^

inArray是一个名称非常糟糕的函数
事实上:(他们应该把它命名为像
indexInArray
之类的东西。@JosephDeeamer:是的。通常的名字是
indexOf
@T.J.Crowder,这是一个非常主流的名字,他们应该做一个更新并逐步淘汰它。谢谢你澄清:P
inArray确实是一个名称非常糟糕的函数
:(他们应该把它命名为
indexInArray
之类的东西。@JosephDeeamer:是的。通常的名字是
indexOf
@T.J.Crowder,这是一个非常主流的名字,他们应该做一个更新并逐步淘汰它。谢谢你的澄清:P