js list

/*列表*/
function List()
{
    this.data = [];
    this.length = 0;
    this.position = 0;


    //判断给定值是否在列表中
    var contains = function(element){
        for(var i=0; i<this.length; ++i){
            if(this.data[i] === element){
                return true;
            }
        }
        return false;
    };
    //从列表中查找元素,成功返回索引,失败返回-1.
    var find = function(element){
        for(var i=0; i<this.length; ++i){
            if(this.data[i] === element){
                return i;
            }
        }
        return -1;
    };
    //为列表末尾追加元素
    var append = function(element){
        this.data[this.length++] = element;
    };
    //向列表元素之后插入
    var insert = function(element,after){
        var index = this.find(after);
        if(index > -1){
            this.data.splice(index,1,element);
            ++this.length;
            return true;
        }
        return false;
    };
    //从列表中删除元素
    var remove = function(element){
        var index = this.find(element);
        if(index > -1){
            this.data.splice(index,1);
            --this.length;
            return true;
        }
        return false;
    };
    //获取列表长度,即列表中元素的个数。
    var size = function(){
        return this.length;
    };
    //显示列表中的元素
    var toString = function(){
        return this.data;
    };
    //清空列表中所有元素
    var clear = function(){
        this.length = 0;
        this.position = 0;
        delete this.data;//删除数组
        this.data = [];
    };

    //当前项目
    var curele = function(){
        return this.data[this.position];
    };
    var curpos = function(){
        return this.position;
    };
    //在列表自由移动
    var front = function(){
        this.position = 0;
    };
    var end = function(){
        this.position = this.length-1;
    };
    var prev = function(){
        if(this.position > 0){
            --this.position;
        }
    };
    var next = function(){
        if(this.position < this.length-1){
            ++this.position;
        }
    };
    var moveto = function(position){
        this.position = position;
    };

    this.append = append;
    this.size = size;
    this.toString = toString;
    this.find = find;
    this.remove = remove;
    this.clear = clear;
    this.contains = contains;
    //当前项目
    this.curele = curele;
    this.curpos = curpos;
    //迭代器行为
    this.front = front;
    this.end = end;
    this.prev = prev;
    this.next = next;
    this.moveto = moveto;
}
0人点赞
javascript


作者:JunChow520
链接:https://www.jianshu.com/p/9ead26d862b8
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

 

posted on 2021-02-28 14:02  DreamOnTheGo  阅读(85)  评论(0编辑  收藏  举报