在for循环中拼接数组中的项目,得到typeerror

Splicing items from an array in a for loop, get typeerror

对于我正在制作的应用程序,我想使用复选框从数组中删除项目。这是我使用的功能:

    for(let article = articleList.length -1; article >= 0; article--)
  
  {
    console.log(article, articleList[article].props.title);
    if(this.whatToShow.article == false){
      if (articleList[article].props.category == "Artikel"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.news == false){
      if (articleList[article].props.category == "Nieuws"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.blog == false){
      if (articleList[article].props.category == "Blog"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.client == false){
      if (articleList[article].props.category == "Client"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.stories == false){
      if (articleList[article].props.category == "Ervaringsverhaal"){
        articleList.splice(article, 1);
      }
    }
  }

我首先遇到的问题是它不会删除所有项目,所以我向后循环。现在,当我关闭几乎所有复选框(所有值均为 false)时,我得到一个类型错误,但我不知道这里出了什么问题。谁能帮帮我?

提前谢谢你:)

发生这种情况是因为在循环中您更改了迭代的数组。

尝试像这样将所有条件包装到 if-else:

  const articleList = [
    { props: { title: 'first', category: 'Artikel' } },
    { props: { title: 'sec', category: 'Blog' } },
    { props: { title: 'third', category: 'Client' } },
    { props: { title: 'fouth', category: 'Nieuws' } },
  ]

  for (let article = articleList.length - 1; article >= 0; article--) {
    console.log(article, articleList[article].props)
    if (this.whatToShow.article == fals && articleList[article].props.category == 'Artikel') {
      articleList.splice(article, 1)
    } else if (this.whatToShow.news == false && articleList[article].props.category == 'Nieuws') {
      articleList.splice(article, 1)
    } else if (this.whatToShow.blog == false && articleList[article].props.category == 'Blog') {
      articleList.splice(article, 1)
    } else if (this.whatToShow.client == false && articleList[article].props.category == 'Client') {
      articleList.splice(article, 1)
    }
  }

或者你也可以使用“continue”代替if-else构造