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

你可能感兴趣的:(JavaScript,js)