2009-08-13 86 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);