我有以下数组设置,我,e:
var myArray = new Array();
Run Code Online (Sandbox Code Playgroud)
使用这个数组,我会在用户添加更多菜单项时动态创建面包屑菜单.我还允许他们通过点击eatch breadcrumb菜单项旁边的十字架来删除特定的面包屑菜单项.
数组可能包含以下数据:
myArray[0] = 'MenuA';
myArray[1] = 'MenuB';
myArray[2] = 'MenuC';
myArray[3] = 'MenuD';
myArray[4] = 'MenuE';
Run Code Online (Sandbox Code Playgroud)
我的问题是:
a)在JavaScript中,如何从myArray中删除元素[1]然后重新计算索引或这是不可能的?
b)如果我不想要菜单选项MenuB,是否需要将其拼接以将其删除?
我的问题是,如果用户删除菜单项以及最后创建新闻,那么这些元素的索引将如何展开?
我只是希望能够删除项目,但不知道如何处理数组索引.
gna*_*arf 30
您可以使用,myArray.push('MenuA');因此在添加元素时不要指定直接数字.
删除元素IE'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"]
Run Code Online (Sandbox Code Playgroud)
CMS*_*CMS 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);
};
Run Code Online (Sandbox Code Playgroud)
用法:
// 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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39422 次 |
| 最近记录: |