簡體   English   中英

從數組javascript中刪除項目

[英]remove item from array 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];

看起來我做錯了什么,請幫助我。

謝謝。

試試這個

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM