javascript - .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(':'))
推荐阅读
- bash - 将用户列表添加到光盘使用命令
- python - 数组 tkinter 条目到标签
- c# - 当我从 SSRS 报告中保存 PDF 时,文本在保存的 PDF 中被重叠或截断
- java-native-interface - 从 cocos2d-x 到 Android 调用 JNI 在 Release 模式下不会触发
- c - 不带参数的 pthread_create 函数
- python - 在Python中首先是高度还是宽度?
- php - 如何从 php 容器中的 dockerfile 运行 composer install
- python - 加载由 tensorflow 训练的 Keras 模型时出错
- xamarin - 如何根据 Selected Bool 参数更改模板控件的属性 (TextColor)?
- asp.net - 通过 React Axios 使用具有相同路由的 Web API 服务