论坛首页 Web前端技术论坛

javascript数组像list一样插入和删除元素

浏览 4113 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2013-05-20  

来自《http://www.yshjava.cn/post/416.html》的一篇文章。

原生的JavaScript数组不能像Java中的List一样在任意位置插入和移除元素,而恰巧很多时候偏偏需要这样的功能,怎么办呢?只好对原生的JavaScript数组做一点扩展了...

扩展的代码非常简单,原理是向JavaScript的数组的原型中添加两个两个函数:insert和remove,分别负责向数组中指定位置插入元素和移除指定位置的元素。代码如下: 

Array.prototype.insert = function(index, value) {
	if(index < 0){
		//如果index位置无效,默认插入到最后一个位置上
		index = this.length;
	}
	var part1 = this.slice(0, index);
	var part2 = this.slice(index);
	part1.push(value);
	return (part1.concat(part2));
};
Array.prototype.remove = function(index) {
	//检查index位置是否有效
	if(index >= 0 && index < this.length){
		var part1 = this.slice(0, index);
		var part2 = this.slice(index);
		part1.pop();
		return (part1.concat(part2));
	}
	return this;
};

 

测试代码如下:

 

var arr = [1, 2, 3];
//遍历原始数组
for(var i = 0; i < arr.length; i++){
	alert(arr[i]);
}
//在第二个位置插入一个新元素
arr = arr.insert(1,'new 2');
//删除第三个位置上的元素
arr = arr.remove(3);
//遍历新数组
for(var i = 0; i < arr.length; i++){
	alert(arr[i]);
}

 

总是觉得这样分隔和连接数组,在性能上可能会有问题,不知道还有没有其它更好的方式....

   发表时间:2013-05-28  
how about json ?

var list = {0: 'first element', 1: 'second element'};

alert(list[2]);
0 请登录后投票
   发表时间:2013-05-30  
不行的,我们要做的是“让数组有在任意位置插入和删除元素的功能”,工作的对象时数组,所以不能用json
0 请登录后投票
   发表时间:2013-06-03  
你知道Array有splice函数么?

The splice() method adds/removes items to/from an array, and returns the removed item(s).


http://www.w3schools.com/jsref/jsref_splice.asp

1 请登录后投票
   发表时间:2013-06-03  
sandy 写道
你知道Array有splice函数么?

The splice() method adds/removes items to/from an array, and returns the removed item(s).


http://www.w3schools.com/jsref/jsref_splice.asp


0 请登录后投票
   发表时间:2013-06-05  
sandy 写道
你知道Array有splice函数么?

The splice() method adds/removes items to/from an array, and returns the removed item(s).


http://www.w3schools.com/jsref/jsref_splice.asp


今天有时间使用你提到的splice函数来扩展Array的插入和移除功能,结果是确实可以,但是性能不如前者高。
Array.prototype.insert = function(index, item){
	this.splice(index, 0, item);
}
Array.prototype.remove = function(index){
	return this.splice(index, 1);
}

前一种方案:

splice方案:

在10000次的插入和移除操作中,速度差距还是很明显的。
0 请登录后投票
论坛首页 Web前端技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics