pop()方法在我的if语句中不起作用



我正试图访问一个如下所示的数组:["12","11","5:","10","1:","12"]。我正在迭代数组的每个组件,并测试数组中的字符串是否有用":"填充的[1]索引,如果是,请使用.pop((方法将其删除。但当我尝试运行它时,控制台会返回Uncaught (in promise) TypeError: firstTwo[i].pop() is not a function。我想知道这是否是因为我试图弹出字符串数据类型?我尝试了切片和拼接,但两者都返回了相似的结果。

for (let i = 0; i < 6; i++) {
console.log(dayInfo[i]); //would print as ex. 12:53:04
firstNum[i] = dayInfo[i][0]; //takes the 1
secondNum[i] = dayInfo[i][1]; //takes the 2
firstTwo[i] = firstNum[i] + "" + secondNum[i]; //Combines the 2 numbers into the array you saw above
if (firstTwo[i][1] === ':') {
firstTwo[i].pop();
}
}

Pop是一个数组方法,它总是从数组中删除最后一个元素,firstTwo[i]不是数组,是元素,调用所需的方法。拼接

这样使用:

firstTwo.splice(i, 1) 

这将删除该元素,但会移动数组索引,所以要小心。

一个更好的方法,也可以与过滤器功能。

firstTwo.filter(e => !e.startsWith(':'))

您的问题在这里

firstTwo[i]=firstNum[i]+""+secondNum[i]; //Combines the 2 numbers into the array you saw above

您在那里键入的内容是否定义了一个名为firstTwo的数组;

如果您想定义一个包含前两个值的数组,请使用正确的语法,如

firstTwo[i]=[firstNum[i],secondNum[i]];

请阅读如何在Javascript中创建数组以获取更多信息

最新更新