从数组javascript中删除项目

时间:2012-11-06 04:59:02

标签: javascript arrays

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

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];

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

感谢。

3 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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);

答案 2 :(得分: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]);
}