首页 > 解决方案 > .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();
  }
}

标签: javascript

解决方案


pop 是一个数组方法,总是会从数组中移除最后一个元素,firstTwo[i]不是数组,是元素,调用你需要的方法。拼接

像这样使用它:

firstTwo.splice(i, 1) 

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

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

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

推荐阅读