【问题标题】:Why is my $.inArray() function not working in voting system?为什么我的 $.inArray() 函数在投票系统中不起作用?
【发布时间】:2015-03-09 01:51:23
【问题描述】:

我想让用户只对帖子投赞成票/反对票一次,所以我想检查用户是否已经投票。但问题是我的函数总是说用户已经投票,而 MongoDB 的投票数组中没有单个 userId。这是函数:

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}});
                }
            }
        }, 

【问题讨论】:

    标签: javascript jquery mongodb meteor


    【解决方案1】:

    inArray 是一个 very 名称不佳的函数:它返回找到该事物的索引,如果未找到则返回 -1,not (顾名思义)true 如果找到,false 如果没有。所以你想要

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

    【讨论】:

    • inArray is a very poorly named function 确实:(
    • 他们应该将其命名为 indexInArray 之类的名称。
    • @JosephtheDreamer:是的。通常的名字是indexOf
    • @T.J.Crowder 这太主流了,他们应该做一个更新并逐步淘汰。
    • 感谢您的澄清:P
    猜你喜欢
    • 2015-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多