列表 Javascript描述

列表
在日常生活中,人们经常使用列表:待办事项列表、购物清单、十佳榜单、最后十名榜单等。当需要保存的元素不是太多,不需要在一个很长的序列中查找元素,或者对其进行排序时,就适合使用列表。
1.定义
function List() {
    this.dataList = [];
    this.listSize = 0;
    this.pos = 0;
    this.len = length;
    this.clear = clear;
    this.toString = toString;
    this.getElement = getElement;
    this.insert = insert;
    this.append = append;
    this.remove = remove;
    this.find = find;
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.contains = contains
}
2.方法
1.添加元素
function append(element) {
    this.dataList[this.listSize++] = element;
}
2.查找元素位置
function find(element) {
    for (var i = 0; i < this.dataList.length; ++i) {
        if (this.dataList[i] == element) {
        return i;
       }
    }
    return -1;
}
3.删除元素
function remove(element) {
    var index = this.find(element);
    if (index > -1) {
        this.dataList.splice(index, 1);
        this.listSize -= 1;
        return true;
    }
    return false;
}
4.查询列表元素个数
function length() {
    return this.listSize;
}
5.显示列表元素
function toString() {
    return this.dataList;
}
6.插入元素
function insert(element, after) {
    var index = this.find(after);
    if (index > -1) {
        this.dataList.splice(index + 1, 0, element);
        this.listSize += 1;
    }else{
        this.append(element);
    }
}
7.清空列表元素
function clear() {
    delete this.dataList;
    this.dataList = [];
    this.pos = 0;
    this.listSize = 0;
    return true;
}
8.查询列表是否包含某元素
function contains(element) {
    for (var i = 0; i < this.dataList.length; ++i) {
        if (this.dataList[i] == element) {
            return true;
        }
    }
    return false;
}
9.改变pos
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(position) {
    this.pos = position;
}
function getElement() {
    return this.dataList[this.pos];
}

参考资料:

    《数据结构与算法JavaScript描述》    Michael McMillan著

猜你喜欢

转载自blog.csdn.net/KysonLai/article/details/80194321
今日推荐