我有以下数组:
{
quiztitle: "Name the US Presidents",
presidents: [
{
president_name: "George Washington",
number: "1",
imgurl: "c-1gw.jpg",
answer_variations: [
"Washington"
]
},
{
president_name: "John Quincy Adams",
number: "6",
imgurl: "c-6ja.jpg",
answer_variations: [
"Adams",
"John Adams"
]
}, .... ect
如何访问答案变体数组并将内容与提交的值进行比较?
我目前有这个代码用于检查总统:
var answer = $('.presidentRow input').val().toLowerCase();
var correct = false;
$.each(data.presidents, function(i, president) {
if ( president.number == questionNumber && president.president_name.toLowerCase() === answer) {
correct = true;
return false;
}
});
此代码获取问题编号并根据总统姓名检查用户提交的值。如果它正确,它会将变量设置为 true,我可以使用它来产生结果。我如何检查提交的答案是否存在变体?
谢谢
最佳答案
另一种比较方式你可以尝试一下~
var answer = $('.presidentRow input').val().toLowerCase();
var correct = false;
$.each(data.presidents, function(i, president) {
if ( president.number == questionNumber) {
if(president.president_name.toLowerCase() === answer){
correct = true;
}else if((','+ president.answer_variations.join().toLowerCase()+',').indexOf(','+answer+',')!=-1){
correct = true;
}
return false;
}
});
编辑
使用Array.join()
将变量作为逗号分隔的字符串,您可以简单地使用String.indexOf()
来检查答案是否存在。
添加','
使答案符合正确的变体选项。
关于javascript - 在 jQuery 中检查/迭代多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31846225/