js循环数组判断数组(数组对象)中是否含有某字段,有的话去除,返回新数组

1) 数组中是否存在指定值,存在就删除
 var array = ['a', 'b', 'c', 'd']
 var index = array.indexOf('c')
 if (index > -1) { // >0表示存在
    array.splice(index, 1) //存在就删除
 }
 console.log(array) //['a', 'b', 'd']
2) 数组对象中是否存在指定值,存在就删除
 var timeList =[
    {caseStage:'退款',operatorTime:'2021-5-27 09:16:16'},
    {caseStage:'退款中',operatorTime:'2021-5-28 09:16:16'},
    {caseStage:'退款失败',operatorTime:'2021-5-28 10:16:16'},
    {caseStage:'退款成功',operatorTime:'2021-5-29 09:16:16'},
 ]
 for (var i = 0; i < this.timeList.length; i++) {
     //判断caseStage为'失败'的对象是否存在
     if (this.timeList[i].caseStage.indexOf('失败') > -1) {
         var index = i
         this.timeList.splice(index, 1) //存在即删除该索引下的对象
    }
 }
  console.log(this.timeList)

但是我用上面这种方法会出bug,然后就用了下面的方法;
新建一个临时数组,把符合条件的放进临时数组,不符合条件的就不管了

 var timeList =[
    {caseStage:'退款',operatorTime:'2021-5-27 09:16:16'},
    {caseStage:'退款中',operatorTime:'2021-5-28 09:16:16'},
    {caseStage:'退款失败',operatorTime:'2021-5-28 10:16:16'},
    {caseStage:'退款成功',operatorTime:'2021-5-29 09:16:16'},
 ]
 var temp_arr = []
 for (var i = 0; i < this.timeList.length; i++) {
     //没有‘失败’字段的,重组临时数组赋值
      if (this.timeList[i].caseStage.indexOf('失败') == -1) {
           var temp_obj = {}
           temp_obj.caseStage = this.timeList[i].caseStage
           temp_obj.operatorTime = this.timeList[i].operatorTime
           temp_arr = temp_arr.concat(temp_obj)
        }
   }
 this.timeList = temp_arr
 console.log(this.timeList) 
 // {caseStage:'退款',operatorTime:'2021-5-27 09:16:16'},
 // {caseStage:'退款中',operatorTime:'2021-5-28 09:16:16'},
 // {caseStage:'退款成功',operatorTime:'2021-5-29 09:16:16'},

出bug的原因:

比如说你的数组是:
【0,1,2,3,4,5】 ,总共6项,i<6对吧,
循环删除数组,比如删除了1,那么数组长度变成了5 ,i<5
继续循环删除了3,数组长度变成了4,i<4,不符合for循环条件
那么在i=4的时候就跳出了循环,相当于只循环了4次,我们是希望循环6次,删除不符合条件的数据的,但结果只循环了4次,所以会出bug

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

铁锤妹妹@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值