zoukankan      html  css  js  c++  java
  • 实现列表类,清空、添加、删除、查找、插入,判断元素是否存在

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

    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' ]
  • 相关阅读:
    彻底屏蔽淘宝网、易趣
    日期处理string 与 DateTime相互转化
    手机进水!!!!!!!!!
    解决VS.net "Automation 服务器不能创建对象"
    综艺大哥大
    计算当前日期是任意时间段内第几周的函数
    吉祥三宝>馒头无极版
    如何在ASP.NET中使用JavaScript脚本
    IDEA工具开发一些辅助功能设置
    Linux命令行模式下挂载U盘与光驱
  • 原文地址:https://www.cnblogs.com/baiyangyuanzi/p/6672651.html
Copyright © 2011-2022 走看看