2012-11-06 40 views
1

我试图从一个数组中删除某些项目,从阵列的JavaScript

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

它的外观像我做错了什么,请帮助我。

谢谢。

+0

你至少可以说明它是如何工作?删除的标准是什么? – Joseph

+0

什么时候定义了你的IDLEN?另外,你的'remove'方法似乎对'Array.splice'很熟悉,你有没有考虑用它来完成你想要的? – Passerby

+0

对不起,编辑提问。 – Red

回答

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); 
+0

感谢它的工作:'我 - ;' – Red

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