3.1 列表的抽象数据类型定义
列表:一组有序的数据。每个列表中的数据称为元素。在JavaScript中列表的元素可以是任意的数据类型。列表中保存的元素没有事先的限定,实际使用时的元素数量受到程序内存的限制。
属性:
listSize: 列表的元素个数
pos: 列表的当前位置
length: 返回列表中元素的个数
方法:
clear(): 清空列S表中的所有元素
toString(): 返回列表的字符串形式
getElement(): 返回当前位置的元素
insert(): 现有元素后插入新元素
append(): 在列表的末尾添加一个元素
remove(): 从列表中移除元素
front(): 从列表的当前位置移动到第一个位置
end(): 从列表的当前位置移动到最后一个位置
prev(): 当前位置后移一位
next(): 当前位置前移一位
currPos(): 返回列表的当前位置
moveTo(): 将当前位置移动到指定位置
创建List列表,及扩展属性方法:
function List() {
this.listSize = 0;
this.pos = 0;
this.dataStore = [];
//面向对象方法不在初始化中,这里只初始化属性
//this.clear = clear;
//this.toString = toString;
//this.insert = insert;
//this.append = append;
//this.remove = remove;
//this.front = front;
//this.end = end;
//this.prev = prev;
//this.currPos = currPos;
//this.moveTo = moveTo;
//this.length = length;
}
//append()方法在列表的末尾插入一个元素:
List.prototype.append = function(element) {
this.dataStore[this.listSize++] = element;
}
//插入的元素赋值给dataStore,同时改变对应的下标;
//find()找到列表中所对应的元素:通过遍历dataStore中的元素,匹配元素是否相等,如果是返回对应的下标,如果不是返回-1;
List.prototype.find = function(element) {
for(var i = 0; i < dataStore.length; i++) {
if(this.dataStore[i] == element) {
return i;
}
}
return -1;
}
//remove()移除列表中的元素:
//首先通过find()方法把所要删除的元素找到,如果存在所要删除的元素,利用数组splice();方法删除,同时listSize列表元素个数减一,删除成功返回true;失败返回false;
List.prototype.remove = function(element) {
var findElement = this.find(element);
if( findElement > -1) {
this.dataStore.splice(findElement,1);
this.listSize--;
return true;
}
return false;
}
//length: 列表length,返回元素的个数
List.prototype.length = function() {
return this.listSize;
}
//toString()显示列表中的元素
List.prototype.toString = function() {
return this.dataStore;
}
//insert()项列表中插入一个元素:
//接受两个参数,一个是插入的元素,一个是插入的位置。该方法使用find()方法找到对应的元素,通过判断该元素是否存在,如果不存在在进行插入操作,不存在则通过数组的splice()方法进行插入,同时改变list列表的元素个数。成功返回true,失败返回false;
List.prototype.insert = function(element,after) {//插入元素,插入位置(从0开始)
var insertPos = this.find(after);
if(insertPos > -1) {
this.dataStore.splice( insertPos+1,0,element );//pos+1数组下标从0开始
this.listSize++;
return true;
}
return false;
}
//clear()清空列表中的所有元素:
//该方法通过delete删除dataStore数组,重新创建空的新数组,然后把list列表的元素个数,当前位置改为0;
List.prototype.clear = function() {
delete this.dataStore;
this.dataStore = [];
this.listSize = this.pos = 0;
}
//contains()判断给定值是否在list列表中
//该方法和find()方法类似,contains方法包含返回true,不包含返回false,find方法查找到该元素,返回该元素的下标,不存在返回-1。
List.prototype.contains = function(element) {
for(var i = 0; i < this.dataSize.length; i++) {
if( this.dataStore[i] == element ) {
return true;
}
}
return false;
}
手机扫一扫
移动阅读更方便
你可能感兴趣的文章