2016-05-22 61 views
0

刪除數組元素我有這樣的數組:搜索和在javascript

A = ['a', 'del', 'b', 'del', 'c'] 

如何刪除的元素刪除,使得結果是,

B = ['a', 'b', 'c'] 

我試圖彈出和的indexOf方法但無法使用

+0

如果你說你嘗試過的東西,它沒有工作,那麼你應該顯示你已經嘗試過,以及爲什麼像「[從JavaScript中的數組中刪除特定元素?](http://stackoverflow.com/questions/5767325)」沒有 幫你。 (我知道這個問題是關於刪除多個元素,不管我引用的只是刪除一個元素,但答案都是針對這兩個元素的)。如果你顯示你的嘗試,那麼也可以告訴你爲什麼你的嘗試不起作用。 –

+0

Howcome,是這個問題不重複的 – Redu

+0

可能的複製(http://stackoverflow.com/questions/20733207/loop-to-remove-an-element-in-array [循環到與多次出現數組中刪除元素] -with-多出現) –

回答

2

使用filter()用於從陣列中過濾元素

var A = ['a', 'del', 'b', 'del', 'c']; 
 

 
var B = A.filter(function(v) { 
 
    return v != 'del'; 
 
}); 
 
    
 
console.log(B);


對於較舊的瀏覽器檢查polyfill option of filter method


在情況下,如果要刪除現有的數組元素,然後使用splice()用一個for循環

var A = ['a', 'del', 'b', 'del', 'c']; 
 

 
for (var i = 0; i < A.length; i++) { 
 
    if (A[i] == 'del') { 
 
    A.splice(i, 1); // remove the eleemnt from array 
 
    i--; // decrement i since one one eleemnt removed from the array 
 
    } 
 
} 
 

 
console.log(A);

+2

_Quiet快!_ :) – Rayon

+0

'filter'創建新的數組,VS'splice'其修改現有陣列。差異可能是至關重要的。 –

+0

@JeremyJStarcher:按的問題,我認爲他需要創建一個新的數組B,'B = [ '一', 'B', 'C']' –