实现列表类,清空、添加、删除、查找、插入,判断元素是否存在

实现列表类,清空、添加、删除、查找、插入,判断元素是否存在

function List() {
    this.listSize = 0;//列表中元素的个数
    this.dataStore = [];//初始化一个空数组来保存数据
    this.clear = clear;//清空列表中的所有元素
    this.find = find;//在列表中查找某一元素
    this.toString = toString;//显示列表中的元素
    this.insert = insert;//向列表中插入一个元素
    this.append = append;//给列表添加元素
    this.remove = remove;//从列表中删除元素
    this.contains = contains;//判断列表中是否存在某一元素
    this.length = length;//列表中有多少个元素
}
function clear(){
    delete this.dataStore;
    this.dataStore = [];
    this.listSize = 0;
    this.pos = 0;
}

function find(element) {
    for (var i = 0; i < this.dataStore.length; ++i) {
        if (this.dataStore[i] == element) {
            return i;
        }
    }
    return -1;
}

function toString(){
    return this.dataStore;
}

function insert(element,after){
    var insertPos = this.find(after);
    if(insertPos > -1){
        this.dataSore.splice(insertPos+1,0,element);
        this.listSize++;
        return true;
    }
    return false;
}

function append(element) {
    this.dataStore[this.listSize++] = element;
}

function remove(element) {
    var foundAt = this.find(element);
    if (foundAt > -1) {
        this.dataStore.splice(foundAt,1);
        this.listSize--;
        return true;
    }
    return false;
}

function contains(){
    for(var i= 0; i < this.dataStore.length;i++){
        if(this.dataStore[i] == element){
            return true;
        }
    }
    return false;
}

function length(){
    return this.listsize;
}


var names = new List();
names.append("Cynthia");
names.append("Raymond");
names.append("Barbara");
console.log(names.toString());//[ 'Cynthia', 'Raymond', 'Barbara' ]
names.remove("Raymond");
console.log(names.toString());//[ 'Cynthia', 'Barbara' ]
原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6672651.html