0
点赞
收藏
分享

微信扫一扫

js 中 forEach无法删除数组项目

三维控件研究 2022-01-20 阅读 113

js 中 forEach无法删除数组项目

原因 :forEach 回调函数 中删除数组中的一项,会导致数组项往前移动,而 index 在下一次就 index++ , 这样就略过了被删除项的后一项,导致出乎意料!

解决方案: for 循环 index–

for (let index = 0; index < data.length; index++) {
  if (data[index].from === 'china') {
    data.splice(index, 1);
    index--
  }
}
举报

相关推荐

0 条评论