• 实现列表项:find()&insert()&remove()&contains()&clear()


        function List() {
            this.listSize = 0;//列表的元素个数,属性
            this.pos = 0;//列表的当前位置,属性
            this.dataStore = []; // 初始化一个空数组来保存列表元素
    
            this.length = length;//返回列表中元素的个数
            this.toString = toString;//返回列表的字符串形式,方法
    
            this.append = append;//在列表的末尾添加新元素,方法
    
            this.find = find;//查找元素的位置,用于辅助    
            this.insert = insert;//在现有元素后插入新元素,方法    
            this.remove = remove;//从列表中删除元素,方法    
            this.contains = contains;
    
            this.clear = clear;//清空列表中的所有元素,方法
        }
    
        function length() {
            return this.listSize;
        }
        function toString() {
            return this.dataStore;
        }
    
        function append(element) {
            this.dataStore[this.listSize++] = element;
            //后自加,在新位置添加元素,同时列表的元素个数加1
        }
    
        function find(element) {
            for ( var i = 0; i < this.dataStore.length; ++i) {
                if (this.dataStore[i] == element) {
                    return i;
                }
            }
            return -1;
        }
        function remove(element) {
            var foundAt = this.find(element);
            if (foundAt > -1) {
                this.dataStore.splice(foundAt, 1);
                --this.listSize;
                return true;
            }
            return false;
        }
        function insert(element, after) {
            var insertPos = this.find(after);
            if (insertPos > -1) {
                this.dataStore.splice(insertPos + 1, 0, element);
                ++this.listSize;
                return true;
            }
            return false;
        }
        function contains(element) {
            for ( var i = 0; i < this.dataStore.length; ++i) {
                if (this.dataStore[i] == element) {
                    return true;
                }
            }
            return false;
        }
    
        function clear() {
            delete this.dataStore;
            this.dataStore = [];
            this.listSize = this.pos = 0;
        }
        
        var names = new List();
        names.append("Cynthia");
        names.append("Raymond");
        names.append("Barbara");
        alert(names.toString());
        names.remove("Raymond");
        alert(names.toString());
  • 相关阅读:
    使用express+multer实现node中的图片上传
    利用H5构建地图和获取定位地点
    移动端开发基础 干货分享
    关于angularJS的一些用法
    你好 JSONP !!!!
    CentOS7使用Alien将RPM从DE转换为DEB和DEB转换为RPM包
    [Windows] visio2019破解激活
    python---九九乘法表代码
    HTTP 请求方式: GET和POST的比较
    win10WLAN没有有效的ip配置
  • 原文地址:https://www.cnblogs.com/feile/p/5371194.html
Copyright © 2020-2023  润新知