gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 21:35:21 25 4
gpt4 key购买 nike

我正在尝试访问如下所示的数组:["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]不是数组,是一个元素,调用你需要的方法。 Splice

像这样使用它:

firstTwo.splice(i, 1) 

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

更好的方法,也可以使用过滤功能。

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

关于javascript - .pop() 方法在我的 if 语句中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60513784/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com