0

我在将对象存储到数组时遇到问题。但是当我尝试使用 $.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"}]
4

2 回答 2

3

您不能使用inArray()简单的方法来比较任何无法比较的东西===

例如:

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

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

IE

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

于 2013-08-15T11:20:17.123 回答
1

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

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

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

然后

ng-click="radioSelected(question)"
于 2013-08-15T11:25:38.267 回答