栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > Web开发 > JavaScript

js 实现List

JavaScript 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js 实现List

列表是一组有序的数据。每个列表中的数据项称为元素。在 Javascript 中,列表中的元素可以是任意数据类型。
我们可以根据数组的特性来实现List。

List 抽象数据类型定义
  • listSize(属性) 列表的元素个数

  • pos(属性) 列表的当前位置

  • length(属性) 返回列表中元素的个数

  • clear(方法) 清空列表中的所有元素

  • toString(方法) 返回列表的字符串形式

  • getElement(方法) 返回当前位置的元素

  • insert(方法) 在现有元素后插入新元素

  • append(方法) 在列表的末尾添加新元素

  • remove(方法) 从列表中删除元素

  • front(方法) 将列表的当前位置设移动到第一个元素

  • end(方法) 将列表的当前位置移动到最后一个元素

  • prev(方法) 将当前位置前移一位

  • next(方法) 将当前位置后移一位

  • currPos(方法) 返回列表的当前位置

  • moveTo(方法) 将当前位置移动到指定位置

实现
class List{    constructor() {        this.dataSouce = [];        this.listSize = 0; // 列表的大小
        this.pos = 0;     // 列表中当前的位置
    }    
    append(element) {        this.dataSouce[this.listSize++] = element;
    }    
    insert(element) {        this.dataSouce.push(element);        this.listSize++;
    }    
    remove(element) {        // 查找当前元素的索引
       const index = this.dataSouce.indexOf(element);       if (index >= 0) {            this.dataSouce.splice(index, 1);            this.listSize--;            return true;
       }       return false;
    }    
    contains(element) {        return this.dataSouce.indexOf(element) > -1;
    }    
    front() {        this.pos = 0;
    }    
    end() {        this.pos = this.listSize - 1;
    }    
    prev() {        if (this.pos > 0) {
            --this.pos;
        }
    }    
    next() {        if (this.pos <= (this.listSize - 1)) {
            ++this.pos;
        }
    }    
    currPos() {        return this.pos;
    }    
    moveTo(position) {        this.pos = position;
    }    
    getElement() {        return this.dataSouce[this.pos];
    }    
    clear() {        delete this.dataSouce;        this.dataSouce = [];
        tihs.listSize = 0;        this.pos = 0;
    }    
    length() {        return this.listSize;
    }    
    toString() {        return this.dataSouce;
    }
}export default List;

原文出处:https://www.cnblogs.com/qiaojie/p/9571990.html

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/246903.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号