This website requires JavaScript.

JS应用splice删除多元素时出现的坑

2018.04.11 11:36字数 2238阅读 307喜欢 0评论 0

经常做后台取数据,渲染到页面工作的前端童鞋可能都碰到过这种需求:那就是如果后台传给前端的数据要二次处理,一个数组,其中具有某种共同特征的元素是我们不需要的,必须要把它删除掉,这时候怎么做呢。

var list=[{"id":"161","balance":"0.02","type":"1","name":"万胜围加油站州博物馆在","address":"广州海珠区万胜围","img":"http://pic-bucket.nosdn.127.net/photo/0001/2018-02-26/DBIGAIN100AP0001NOS.jpg?imageView&thumbnail=900y600","fuel_id":"1","code":"5250289976129518","code_img":"","is_recommended":0,"distance":0,"latitude":"23.1020540","longitude":"113.3895850","status":1},{"id":"162","balance":"0.02","type":"1","name":"万胜围加油站州博物馆在","address":"广州海珠区万胜围","img":"http://pic-bucket.nosdn.127.net/photo/0001/2018-02-26/DBIGAIN100AP0001NOS.jpg?imageView&thumbnail=900y600","fuel_id":"1","code":"5250289976129518","code_img":"","is_recommended":0,"distance":0,"latitude":"23.1020540","longitude":"113.3895850","status":2},{"id":"163","balance":"0.02","type":"1","name":"万胜围加油站州博物馆在","address":"广州海珠区万胜围","img":"http://pic-bucket.nosdn.127.net/photo/0001/2018-02-26/DBIGAIN100AP0001NOS.jpg?imageView&thumbnail=900y600","fuel_id":"1","code":"5250289976129518","code_img":"","is_recommended":0,"distance":0,"latitude":"23.1020540","longitude":"113.3895850","status":2},{"id":"164","balance":"0.02","type":"1","name":"万胜围加油站州博物馆在","address":"广州海珠区万胜围","img":"http://pic-bucket.nosdn.127.net/photo/0001/2018-02-26/DBIGAIN100AP0001NOS.jpg?imageView&thumbnail=900y600","fuel_id":"1","code":"5250289976129518","code_img":"","is_recommended":0,"distance":0,"latitude":"23.1020540","longitude":"113.3895850","status":1}];

拿到这段数据,去除status为2的,A君想当然的写了下面的代码:

for (var i = 0, k = list.length-1; i < k; i++) {
    if (list[i].status == 2) {
      list.splice(i, 1);
    }
}

console.log(list)

{id: "161"...},{id: "163"...},{id: "164"...}

然后打印出来,哎呀,不对,之后又改成了下面的方法

for (var i = 0, k = list.length, s = 0; i < k; i++) {
    if (list[i - s].status == 2) {
      list.splice(i - s, 1);
      s++;
    }
}
console.log(list)
{id: "161"...},{id: "164"...}

然后B君看了看,写了下面这段

for(var i=0,flag=true,len=list.length;i<len;flag ? i++ : i){
    if( list[i]&&list[i].status==2){
        list.splice(i,1);
         flag = false;
     } else {
         flag = true;
     }
 }
 console.log(list)
 {id: "161"...},{id: "164"...}

后面来个C君,他说有一句话的实现方法,知道的可以留言...