arrays - 如果javascript中不存在值,如何推送到多维数组
问题描述
我有一个多维数组,用于存储有关用户给出的问题和答案的信息,并依赖于 3 次检查。
- 如果数组为空,则推送初始数据集
- 如果数组中存在问题编号,则更新其相关答案
- 如果一个问题编号不存在,则将问题信息和答案推送到数组中
我已经设法进行了前 2 次检查,但我在进行第三次检查时遇到了问题。当我尝试推送新的问答信息时,它会推送多次重复,而不仅仅是一个数据集。
我正在使用的功能是:
getBoolvalue(boolvalue, optionIndex, questionnNumber, option)
{
if(this.answerboolvalues[0] == null)
{
this.answerboolvalues.push([questionnNumber, optionIndex, option, boolvalue]);
console.log(this.answerboolvalues);
}
else
{
console.log("Array length : " + this.answerboolvalues.length);
console.log("Array item : " + this.answerboolvalues[1][2]);
for(let j = 0; j < this.answerboolvalues.length; j++)
{
if(this.answerboolvalues[j][0] == questionnNumber)
{
if(this.answerboolvalues[j][1] == optionIndex)
{
this.answerboolvalues[j][3] = boolvalue;
console.log(this.answerboolvalues);
}
}
else if(this.answerboolvalues[j][0] != questionnNumber)
{
this.answerboolvalues.push([questionnNumber, optionIndex, option, boolvalue]);
}
}
}
}
解决方案
.find
使用它来查看元素是否存在于数组中会更干净。如果是这样,您可以根据需要对找到的项目进行变异,否则推送一个新数组。
不需要if(this.answerboolvalues[0] == null)
检查,因为如果数组为空,将找不到任何元素,所以无论如何都会因为条件3而被推送到数组中。
还要修复questionNumber
拼写错误,错别字是错误的一个简单来源:
getBoolvalue(boolValue, optionIndex, questionNumber, option) {
const foundItem = this.answerboolvalues.find(
subarr => subarr[0] === questionNumber && subarr[1] === optionIndex
);
if (foundItem) {
foundItem[3] = boolValue;
} else {
this.answerboolvalues.push([questionNumber, optionIndex, option, boolValue]);
}
}
但是这个数据结构很奇怪。考虑改为answerboolvalues
索引的对象questionNumber
,或者将其作为对象数组而不是数组数组:
getBoolvalue(boolValue, optionIndex, questionNumber, option) {
const foundItem = this.answerboolvalues.find(
subarr => subarr.questionNumber === questionNumber && subarr.optionIndex === optionIndex
);
if (foundItem) {
foundItem.boolValue = boolValue;
} else {
this.answerboolvalues.push({ questionnNumber, optionIndex, option, boolValue });
}
}
推荐阅读
- unit-testing - 当 PartialEq 的实现不合适时,如何断言两个变量相等?
- arrays - GLSL 动态数组索引
- gcc - 将表格添加到rodata段的链接器脚本
- vscode-settings - VSCode 终端 - echo $SHELL 显示 bash,但我已将 shell 设置为 zsh
- javascript - 如何获取另一个网站的屏幕截图/预览
- nginx - Nginx 将根目录设置为子文件夹
- javascript - 不同计算机上的列宽不同
- vue.js - 如何在 VueJS v-for 循环中设置临时变量
- graphql - 收到此错误:错误:重新渲染太多。React 限制渲染次数以防止无限循环
- javascript - 如何在 JavaScript 中舍入和格式化数字而不用尾随零?