javascript实现列表类

什么是列表?例如你会对你接下来一周要做的事情,你会根据时间先后记载笔记本上或者手机的备忘录里,又或者你淘宝上的购物车,它们都是列表的一种体现。也就是说列表是一组有序的数据。这里不难看出“有序”是列表的一个重要特性。列表中,可以存储任意数据类型,存储的数据量受制于程序的内存,你可以定义很多种方法来对列表里的元素进行操作。接下来我们实现一个简单的列表类:

1 新建一个构造函数

//构造函数
function List(){
    this.listSize = 0;
    this.pos = 0;
    this.dataStore = [];//初始化一个空数组保存列表元素
     //方法
     this.clear = clear;
    this.find = find;
    this.toString = toString;
    this.insert = insert;
    this.append = append;
    this.remove = remove;
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.length = length;
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.getElement = getElement;
    this.contains = contains;
}

2 定义方法

//给列表添加新元素
function append(element) {
    this.dataStore[this.listSize++] = element;
}
//查找列表元素
function find(element) {
    for(let i = 0; i < this.dataStore.length; i++) {
        if(this.dataStore[i] == element)
            return i;
    }
    return -1;
}
//从列表中删除元素
function remove(element) {
    let foundAt = this.find(element);
    if(foundAt > -1) {
        this.dataStore.splice(foundAt, 1);
        --this.listSize;
        return true;
    }
    return false;
}
//列表中元素的个数(长度)
function length() {
    return this.listSize;
}
//显示列表中的元素
function toString() {
    return this.dataStore;
}

//向列表插入新元素
function insert(element, after) {
    let insertPos = this.find(after);
    if(insertPos > -1) {
        this.dataStore.splice(insertPos + 1, 0, element);
        ++this.listSize;
        return true;
    }

    return false;
}
//清空列表
function clear() {
    delete this.dataStore;
    this.dataStore = [];
    this.listSize = this.pos = 0;
}
//判断给定值是否在列表中
function contains(element) {
    for(let i = 0; i < this.dataStore.length; i++) {
        if(this.dataStore[i] == element) {
            return true;
        }
    }
    return false;
}
//最前位置
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.dataStore[this.pos];
}

3 测试

测试我们选择在控制台来进行测试,直接在控制台输入指令就可以,现在源代码中新建一个列表对象:
//新建一个列表对象
let newList = new List();
接下来运行程序,在浏览器控制台输入,在控制台输入代码换行的快捷键:Enter + shift; 先给newList添加元素:


在列表里查找元素,和插入元素:


再从列表移除元素


判断元素是否在列表中:

其他方法的应用:


上述实现了大部分功能,未实现的请读者自己实现哈!
本文我们实现了一个列表类,虽然列表应用极大的方便了我们存储数据,但它也有其缺点:如果数据结构非常发杂,用列表就显得意义不大。

猜你喜欢

转载自blog.csdn.net/qq_37338983/article/details/78825016