我遇到有关将对象存储到数组中的问题。但是当我尝试使用$ .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"}]
答案 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)"