首页 > 解决方案 > 如果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]);
            }
        }
    }

}

标签: arraystypescriptfor-loopif-statementmultidimensional-array

解决方案


.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 });
  }
}

推荐阅读