Javascript 如何使用if语句检查数组中的任何值是否显示true值?
我的目标如下:Javascript 如何使用if语句检查数组中的任何值是否显示true值?,javascript,Javascript,我的目标如下: var myObj = {"qId":"726112", "text":"xx", "answers":[{"answerId":null, "answerUId":1, "text":"xx", "correct":null, "response":false}, {"answerId":null, "answerUId
var myObj =
{"qId":"726112",
"text":"xx",
"answers":[{"answerId":null,
"answerUId":1,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":2,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":4,
"text":"xx",
"correct":null,
"response":false}]}
有人能告诉我如何使用if语句来检查响应字段中是否有任何一个的值为true吗?您可以使用函数,如果至少有一个元素返回true
,则该函数返回true
,如下所示
if (myObj.answers.some(function(answer) { return answer.response; })) {
# Atleast one of them is true
}
如果要查找数组中响应的更改状态是真是假。你很容易理解 var myObj= {“qId”:“726112” “文本”:“xx” “答案”: [{“answerId”:空, 答案:1, “文本”:“xx”, “正确”:空, “响应”:true} 如果(myObj.answers.length>0){ } 输出: myObj对象中answers数组的第0个索引为true myObj对象中answers数组的第1个索引为false
2 myObj对象中的answers数组索引为true无法满足您的要求,请澄清,检查响应字段中是否有一个值为true是什么意思。该对象有一个名为answers的属性,该属性包含一个对象数组。如果这些数组中的响应属性中有一个值为true,这就是我需要知道的。格式化代码和输出会很有帮助。
{"answerId":null,
"answerUId":2,
"text":"xx",
"correct":null,
"response":false},
{"answerId":null,
"answerUId":4,
"text":"xx",
"correct":null,
"response":true}]
};
for (var i in myObj.answers){
if(myObj.answers[i].response){
console.log(i+"th index of answers Array in myObj object has "+myObj.answers[i].response);
}
else{
console.log(i+"th index of answers Array in myObj object has "+myObj.answers[i].response);
}
}