1

我试图从数组中删除一些项目,

Array.prototype.remove = function(from, to)
{
      var rest = this.slice((to || from) + 1 || this.length);
     this.length = from < 0 ? this.length + from : from;
      return this.push.apply(this, rest);
};

var BOM = [0,1,0,1,0,1,1];


var IDLEN = BOM.length;

for(var i = 0; i < IDLEN ;++i)
{

     if( BOM[i] == 1) 
     {
         BOM.remove(i);
     //IDLEN--;
     }

} 

结果是

   BOM = [0,0,0,1];

预期的结果是

   BOM = [0,0,0];

看起来我做错了什么,请帮助我。

谢谢。

4

3 回答 3

4

试试这个

var BOM = [0,1,0,1,0,1,1];
for(var i = 0; i < BOM.length;i++){
  if( BOM[i] == 1) {
     BOM.splice(i,1); 
     i--;
  }
} 
console.log(BOM);
于 2012-11-06T05:10:16.890 回答
1
Try using filter:    

var test1 = ['a','b','c','d'];
var test2 = ['b','c'];

test2.forEach(removeItem => 
{
  test1 = test1.filter(item => item != removeItem);
})

console.log('Modified array',test1);
于 2020-04-29T05:07:07.727 回答
0
Array.prototype.remove= function(){
    var what, a= arguments, L= a.length, ax;
    while(L && this.length){
        what= a[--L];
        while((ax= this.indexOf(what))!= -1){
            this.splice(ax, 1);
        }
    }
    return this;
}

调用这个函数

for(var i = 0; i < BOM.length; i++)
{
    if(BOM[i] === 1) 
      BOM.remove(BOM[i]);
}
于 2012-11-06T05:16:05.903 回答