2009-08-13 61 views
4

我有以下陣列設置,I,E:JavaScript數組 - 移除數組元素

var myArray = new Array(); 

使用此陣,我創建一個麪包屑動態菜單爲用戶增加了更多的菜單項。我還允許他們通過點擊eatch breadcrumb菜單項旁邊的十字線來刪除特定的麪包屑菜單項。

陣列可以保持以下數據:

myArray[0] = 'MenuA'; 
myArray[1] = 'MenuB'; 
myArray[2] = 'MenuC'; 
myArray[3] = 'MenuD'; 
myArray[4] = 'MenuE'; 

我的問題是:

一個)在JavaScript中,如何可以從myArray的移除元件[1],然後重新計算索引或這是不可能?

b)如果我不想要菜單選項MenuB,我需要拼接它以將其刪除嗎?

我的問題是,如果用戶刪除菜單項以及在最後創建新聞,那麼這些元素的索引將如何展開?

我只是想能夠刪除項目,但不知道如何處理數組索引。

謝謝。 Tony。

回答

20

我喜歡Array.remove的this implementation,它基本上是抽象的使用splice功能:

// Array Remove - By John Resig (MIT Licensed) 
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); 
}; 

用法:

// Remove the second item from the array 
array.remove(1); 
// Remove the second-to-last item from the array 
array.remove(-2); 
// Remove the second and third items from the array 
array.remove(1,2); 
// Remove the last and second-to-last items from the array 
array.remove(-2,-1); 
+0

感謝CMS和其他回覆的人。 – tonyf 2009-08-14 01:27:12

+3

你可以更多地表達我嗎?我沒有理由,爲什麼不使用簡單的splice native方法從數組中刪除元素。 – 2010-10-20 15:53:34

+0

我認爲拼接很好,而不是寫你自己的代碼。 – Rajkishore 2015-06-27 08:30:16

27

您可以使用myArray.push('MenuA');,因此添加元素時不指定直接數字。

刪除元素I.E. 'MenuB':

// another quick way to define an array 
myArray = ['MenuA', 'MenuB', 'MenuC', 'MenuD', 'MenuE']; 

// remove an item by value: 
myArray.splice(myArray.indexOf('MenuB'),1); 

// push a new one on 
myArray.push('MenuZ'); 

// myArray === ["MenuA", "MenuC", "MenuD", "MenuE", "MenuZ"] 
+3

indexOf對於在IE上不支持的數組。它可以被原型 - > http://stackoverflow.com/questions/1744310/how-to-fix-array-indexof-in-javascript-for-ie-browsers – vsync 2010-05-04 12:17:24

+0

如果你使用jQuery,它提供了內置的indexOf數組 - > http://api.jquery.com/jQuery.inArray/ – vsync 2010-05-04 12:20:28

0

你並不需要編寫一個函數,可以使用indexOf()和splice()這兩個函數。

您可以刪除元素的任何位置元素。 例如: var name = ['james','tommy','Jimmy','Holon']; var name = name.splice(name.indexOf('Jimmy'),1);