【问题标题】:splice method returns an error: is not a functionsplice 方法返回错误:不是函数
【发布时间】:2021-03-30 06:12:37
【问题描述】:

我一直在尝试使下面的代码工作,这是删除功能的一部分。 但是,for循环中的splice方法在运行时一直返回错误。

谁能帮我解决这个问题?

let games = JSON.parse(localStorage.getItem('games'));

for (let i =0; i < games.length; i++) {
    if (games[i].gName == gName) {
        console.log('found it');
        games[i].splice(i, 1);
        //Uncaught TypeError: games[i].splice is not a function
    }
}

【问题讨论】:

  • games 是一个数组。您似乎将元素置于数组的位置i 并尝试splice(...) 此元素。我想你的意思是 splice(...) 那个位置的数组?
  • 是的,这就是我的本意。我对这两个 i 感到困惑:一个在 [] 中,另一个在 () 中。感谢您详细说明我的问题!

标签: javascript arrays for-loop methods splice


【解决方案1】:

我认为 splice 函数会返回错误,因为 games[i] 是一个对象,而不是一个数组。 如果要在阵列上使用拼接,只需删除 [i] 部分。 games.splice(i, 1);

您也可以使用for (i in games) 作为for (let i =0; i &lt; games.length; i++); 的简写

【讨论】:

  • 非常感谢您的帮助!现在整个事情都在工作!
猜你喜欢
  • 1970-01-01
  • 2021-08-17
  • 2020-04-17
  • 2019-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
相关资源
最近更新 更多