JavaScript列表
1 什么是列表
列表是一组有序的数据,每个列表中的数据项称为元素。当需要在一个不是很长的序列中查找元素或者对其进行排序时,列表显得尤为有用。在JavaScript中,元素可以是任何类型。
2 列表的结构
列表的抽象数据类型并未指明存储结构,此处使用数组dataStore来存储元素。完整的属性/方法定义如下:
属性 | 含义 |
---|---|
listSize | 元素个数 |
pos | 当前元素位置 |
方法 | 含义 |
---|---|
length() | 返回元素个数 |
append() | 在列表末尾添加元素 |
insert() | 在列表指定位置插入元素 |
remove() | 从列表中删除元素 |
clear() | 清空列表 |
contains() | 返回列表是否包含该元素 |
find() | 在列表中查找元素 |
front() | 将列表当前位置移动到第一个元素 |
end() | 将列表当前位置移动到最后一个元素 |
moveTo() | 将列表当前位置移动到指定位置 |
getElement() | 返回列表当前位置元素 |
prev() | 将当前位置往后移动一位 |
next() | 将当前位置往前移动一位 |
currPos() | 返回列表当前位置 |
toString() | 返回列表的字符串形式 |
方法分为:返回元素个数/返回当前元素位置/增删查列表元素/遍历列表元素/列表字符串形式表示
3 列表的实现
3.1 列表构造函数
function List(){
this.dataStore=[];//空数组初始化 用于存放元素
//以下是属性
this.listSize=0;
this.pos=0;
//以下是方法
this.currPos = currPos;//获取当前元素位置/元素个数
this.length = length;
this.append = append;//增
this.insert = insert;
this.remove = remove;//删
this.clear = clear;
this.contains = contains;//查
this.find = find;
this.getElement = getElement;
this.front = front;//遍历时指针的移动
this.end = end;
this.prev = prev;
this.next = next;
this.moveTo = moveTo;
this.toString = toString;
}
3.2 列表方法的实现
3.2.1 currPos()
function currPos(){
return this.pos;
}
3.2.2 length()
function length(){
return this.listSize;
}
3.2.3 append()
function append(item){
this.dataStore[this.listSize++]=item;
}
3.2.4 insert()
插入到列表某个元素之后
function insert(item,element){
var insertPos=this.dataStore.find(element);
if(insertPos>-1){
this.dataStore.splice(insertPos+1,0,item);
this.listSize++;
return true;//插入成功
}else{
return false;//插入失败
}
}
3.2.5 remove()
从列表中删除元素
function remove(item){
var removePos=this.dataStore.find(item);
if(removePos>-1){
this.dataStore.splice(removePos,1);
this.listSize--;
return true;//删除成功
}else{
return false;//删除失败
}
}
3.2.6 clear()
function clear(){
delete this.dataStore;
this.dataStore=[];
this.listSize=0;
this.pos=0;
}
3.2.7 contains()
function contains(item){
for(var i=0;i<this.dataStore.listSize;i++){
if(this.dataStore[i]===item){
return true;
}
}
return false;
}
3.2.7 find()
function find(item){
for(var i=0;i<this.dataStore.listSize;i++){
if(this.dataStore[i]===item){
return i;
}
}
return -1;
}
3.2.7 遍历列表
function front(){
this.pos=0;
}
function end(){
this.pos=this.listSize-1;
}
function prev(){
if(this.pos>0){
this.pos--;
}
}
function next(){
if(this.pos<this.listSize-1){
this.pos++;
}
}
function currPos(){
return this.pos;
}
function moveTo(index){
this.pos=index;
}
function getElement(){
return this.dataStore[this.pos];
}
3.3 使用迭代器访问列表
优点:前面的方法就实现了列表类的一个迭代器,相比数组索引方式而言,这种方式不必关心数据的内部存储结构,提供了一种统一方式。且列表添加元素后进行遍历不用更新迭代器。
从前向后遍历:
var newList=new List();
...
for(newList.front();newList.currPos()<newList.length();newList.next()){
console.log(newList.getElement());
}
从后向前遍历:
var newList=new List();
...
for(newList.end();newList.currPos()>=0;newList.prev()){
console.log(newList.getElement());
}
//是>=0,不是front(),前者是固定数值,后者是改变指针的位置,会出现问题。
以上两种遍历方式本质都是this.pos指针的修改然后取得pos位置对应的元素。