首页 > web前端 > js教程 > 正文

js实现ArrayList功能附实例代码

PHP中文网
发布: 2017-03-17 17:19:39
原创
1507 人浏览过

1.ArrayList方法摘要

构造方法摘要

ArrayList() 
构造一个初始容量为 10 的空列表。 
ArrayList(Collection c) 
构造一个包含指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排列的。 
ArrayList(int initialCapacity) 
构造一个具有指定初始容量的空列表。 
方法摘要 
boolean add(E e) 
将指定的元素添加到此列表的尾部。 
void add(int index, E element) 
将指定的元素插入此列表中的指定位置。 
boolean addAll(Collection c) 
按照指定 collection 的迭代器所返回的元素顺序,将该 collection 中的所有元素添加到此列表的尾部。 
boolean addAll(int index, Collection c) 
从指定的位置开始,将指定 collection 中的所有元素插入到此列表中。 
void clear() 
移除此列表中的所有元素。 
Object clone() 
返回此 ArrayList 实例的浅表副本。 
boolean contains(Object o) 
如果此列表中包含指定的元素,则返回 true。 
void ensureCapacity(int minCapacity) 
如有必要,增加此 ArrayList 实例的容量,以确保它至少能够容纳最小容量参数所指定的元素数。 
E get(int index) 
返回此列表中指定位置上的元素。 
int indexOf(Object o) 
返回此列表中首次出现的指定元素的索引,或如果此列表不包含元素,则返回 -1。 
boolean isEmpty() 
如果此列表中没有元素,则返回 true 
int lastIndexOf(Object o) 
返回此列表中最后一次出现的指定元素的索引,或如果此列表不包含索引,则返回 -1。 
E remove(int index) 
移除此列表中指定位置上的元素。 
boolean remove(Object o) 
移除此列表中首次出现的指定元素(如果存在)。 
protected void removeRange(int fromIndex, int toIndex) 
移除列表中索引在 fromIndex(包括)和 toIndex(不包括)之间的所有元素。 
E set(int index, E element) 
用指定的元素替代此列表中指定位置上的元素。 
int size() 
返回此列表中的元素数。 
Object[] toArray() 
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。 
T[] toArray(T[] a) 
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。 
void trimToSize() 
将此 ArrayList 实例的容量调整为列表的当前大小。

2.js实现部分功能

<html> 
<script type="text/javascript" src="json.js?1.1.9"></script> 
<head> 
<script type="text/javascript"> 
function ArrayList(){ 
this.arr=[], 
this.size=function(){ 
return this.arr.length; 
}, 
this.add=function(){ 
if(arguments.length==1){ 
this.arr.push(arguments[0]); 
}else if(arguments.length>=2){ 
var deleteItem=this.arr[arguments[0]]; 
this.arr.splice(arguments[0],1,arguments[1],deleteItem) 
} 
return this; 
}, 
this.get=function(index){ 
return this.arr[index]; 
}, 
this.removeIndex=function(index){ 
this.arr.splice(index,1); 
}, 
this.removeObj=function(obj){ 
this.removeIndex(this.indexOf(obj)); 
}, 
this.indexOf=function(obj){ 
for(var i=0;i<this.arr.length;i++){ 
if (this.arr[i]===obj) { 
return i; 
}; 
} 
return -1; 
}, 
this.isEmpty=function(){ 
return this.arr.length==0; 
}, 
this.clear=function(){ 
this.arr=[]; 
}, 
this.contains=function(obj){ 
return this.indexOf(obj)!=-1; 
} 

}; 

//新建一个List 
var list=new ArrayList(); 
//增加一个元素 
list.add("0").add("1").add("2").add("3"); 
//增加指定位置 
list.add(2,"22222222222"); 
//删除指定元素 
list.removeObj("3"); 
//删除指定位置元素 
list.removeIndex(0); 

for(var i=0;i<list.size();i++){ 
document.writeln(list.get(i)); 
} 
document.writeln(list.contains("2")) 
</script> 
</head> 
<body> 
</body> 

</html>
登录后复制

相关文章:

详细介绍用C#描述数据结构3:ArrayList的图文代码

PHP实现C#山寨ArrayList的方法

Java集合之ArrayList示例代码分析

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!