javascript - 将样式添加到另一个对象数组中的数组元素
问题描述
我有一个数组,代表问题编号。
还有另一个对象数组,其中包含用户答案(问题编号以及用户的答案是正确还是错误)。
questions = [] // question numbers
validity = [{answer: true, questionNo: "2"},{answer: false, questionNo: "3"}] // user answers array
我想要做的是,用绿色突出显示正确的问题,用红色突出显示错误的问题。
当数组有两条记录时,我在下面尝试过validity
,但是,它只突出显示最后一条记录:
{
questions.map((i, index) => {
let className = '';
if (validity) {
validity.map((data) => {
if (Object.keys(data).length) {
if ((Number(data.questionNo) === index)) {
if (data.answer) {
className = `question-list correct-q` // when answer `true`,set div to green color
} else {
className = `question-list wrong-q` // when answer `false`,set div to red
}
} else {
className = `question-list` // default div color
}
}
})
} else {
className = `question-list`
}
return (index != 0) &&
<div
className={className}
key={index}
onClick={() => onclickQuestion(index)}
>
Q - {index}
</div>
})
}
我想同时Q-2
用绿色和Q-3
红色着色。
解决方案
您可以使用以下方法找到有效性对象Array.find()
:
{
questions.map((i, index) => {
let className = 'question-list'; // default
const answerObj = validity.find(answer => answer.questionNo == index);
const isValid = answerObj.answer;
if (isValid) {
className = 'question-list correct-q' // when answer "true", set div to green color
} else {
className = 'question-list wrong-q' // when answer "false", set div to red
}
})
// ...
}
推荐阅读
- javascript - Jquery 和菜单和徽标
- android - Android Sqlite,Toast 显示数据已插入但未插入
- javascript - 更改子组件的状态
- vue.js - Vuetify 嵌套表单元素不适用于 $refs
- hive - Hive 问题 - Rank() OVER (PARTITION BY Dept ORDER BY sum(salary))
- ruby-on-rails - 在自定义 Rails 生成器中使用 class_name
- html - Bootstrap 拆分进度条
- c# - OpenXML 创建的电子表格发现不可读的内容
- azure-cosmosdb - 如何在 Azure Cosmos DB SQL API 中使用 SQL 参数进行 CONTAINS 查询?
- html - Html.DropDownListFor 不会将值选择到属性中