$ .inArray不工作

时间:2013-08-15 11:17:01

标签: jquery angularjs arraylist

我遇到有关将对象存储到数组中的问题。但是当我尝试使用$ .inArray检查对象的存在时,它总是返回-1。我正在使用angularjs。

<input name="{{question.number}}"
            ng-click="radioSelected(question.choiceOneWeight, question.number,question.tmiGroup)"
            type="radio" value="{{question.choiceOneWeight}}" />



$scope.radioSelected = function(choice, question, tmiGroup) {
        var answer = {};
        answer.questionNumber = question;
        answer.answerWeight = choice;
        answer.tmiGroup = tmiGroup;

        if($.inArray(answer,userAnswers) < 0){
            userAnswers.push(answer);
        }
    };

我生成的答案对象是

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"}

如果我多次点击单选按钮,

userAnswers数组如下所示:

[{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},
{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},


{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"},

{"questionNumber":23,"answerWeight":1,"tmiGroup":"JP"}]

2 个答案:

答案 0 :(得分:3)

您不能使用 inArray() 来比较使用简单===

无法比较的任何内容

例如:

var a = [{x: 1}];
$.inArray({x: 1}, a); // => -1

在您的情况下,您可以在数组中存储每个问题的JSON字符串版本,然后在其上使用.inArray()

var answer = JSON.stringify({
    questionNumber: question,
    answerWeight: choice,
    tmiGroup: tmiGroup
});

// now you can use inArray as 'answer' is nothing but a string (JSON)
if($.inArray(answer, userAnswers) < 0){
    userAnswers.push(answer);
}

JSON.parse()

中检索问题时,请务必执行userAnswers

答案 1 :(得分:1)

在javascript中,如果对象都引用相同的对象,则它们只被视为彼此相等。在您的情况下,虽然answer可能具有与数组中的对象完全相同的属性和值,但它是一个不同的对象,因此被认为不相等。

您需要将确切的对象传递给函数:

$scope.radioSelected = function(answer) {
    if($.inArray(answer,userAnswers) < 0){
        userAnswers.push(answer);
    }
});

然后

ng-click="radioSelected(question)"