从JavaScript数组中删除元素 [英] Removing elements from JavaScript arrays

查看:109
本文介绍了从JavaScript数组中删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下数组设置,i,e:

I have the following array setup, i,e:

var myArray = new Array();

使用此数组,我会在用户添加更多菜单项时动态创建面包屑菜单。我还允许他们通过点击eatch breadcrumb菜单项旁边的十字架来删除特定的面包屑菜单项。

Using this array, I am creating a breadcrumb menu dynamically as the user adds more menu items. I am also allowing them to removing specific breadcrumb menu items by clicking on the cross alongside eatch breadcrumb menu item.

数组可能包含以下数据:

Array may hold the following data:

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

我的问题是:

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

a) In JavaScript, how can I remove element [1] from myArray and then recalculate indexes or is this not possible?

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

b) If I don't want menu option MenuB, do I need to splice it to remove it?

我的问题是,如果用户删除菜单项以及最后创建新闻,那么索引将如何这些元素是分散的吗?

My problem is, if the user removes menu items as well as create news one at the end, how will the indexes to these elements be spreadout?

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

I just want to be able to remove items but don't know how the array indexes are handled.

推荐答案

我喜欢这个实现 of Array.remove,它基本上抽象使用了 splice function:

I like this implementation of Array.remove, it basically abstracts the use of the splice function:

// 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);

这篇关于从JavaScript数组中删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆