从JavaScript数组中删除元素

4

I have the following array setup, i,e:

var myArray = new Array();

我使用这个数组来动态创建面包屑导航菜单,随着用户添加更多的菜单项。我还允许他们通过点击每个面包屑菜单项旁边的叉号来删除特定的面包屑菜单项。

数组可能包含以下数据:

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

我的问题是:

a)在JavaScript中,我如何从myArray中删除元素[1],然后重新计算索引,或者这不可能吗?

b)如果我不想要菜单选项MenuB,我需要拼接它来删除它吗?

我的问题是,如果用户删除菜单项并在末尾创建新的菜单项,这些元素的索引将如何分布?

我只想能够删除项目,但不知道如何处理数组索引。

5个回答

30
你可以使用myArray.push('MenuA');,这样在添加元素时就不需要直接指定数字。
要删除一个元素,例如'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
IE浏览器不支持数组的indexOf方法,但可以使用原型来实现 -> https://dev59.com/MnI-5IYBdhLWcg3wpqMK。 - vsync
如果您使用jQuery,它为数组提供了内置的indexOf函数 -> http://api.jquery.com/jQuery.inArray/ - vsync

20

我喜欢 这个实现 的 Array.remove,它基本上抽象了 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);

感谢CMS和其他回复的人。 - tonyf
3
可以,请问您能否再解释一下?我不理解为什么不直接使用简单的splice本地方法从数组中删除元素。 - Marco Demaio

3

0

按位置/元素删除数组元素(实际修改数组)

1 - arr.splice(1, 1) -----> (索引,元素数量)

2 - arr.splice(arr.indexOf(5), 1) -----> (array.indexOf(输入值),元素数量)

let arr = [1,2,3,4,5];
console.log(arr.splice(1,1));                // [2]
console.log(arr.splice(arr.indexOf(5), 1));  // [5]
console.log(arr);                            // [1, 3, 4]

按位置/元素删除数组元素(创建副本数组)

let arr2 = [10, 20, 30, 40]
let result = arr2.filter(a=> a!==20);
let result2 = arr2.filter(a=> a!==arr2[arr2.indexOf(30)])
console.log(result)    // [10, 30, 40]
console.log(result2)   // [10, 20, 40]


0

您不需要编写一个函数,可以使用indexOf() 和 splice()这两个函数。

您可以删除任何位置元素。 例如: var name = ['詹姆斯' , '汤米' , '吉米' , '霍隆']; var name = name.splice(name.indexOf('吉米') , 1);


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接