關於JS數據結構 之 列表

1.概念

列表是一組有序數據的集合,其中的每項數據被稱爲 元素 。在js中,列表中的元素能夠是任意數據類型。列表中能夠保存任意多個元素(在實際使用時會受到程序內存的限制)。數組

2.屬性和方法

列表中有一些常見的屬性和方法,下面一一列舉:app

  • listSize(屬性) :列表的元素個數
  • position(屬性) :列表當前的位置
  • clear(方法):清空列表中的全部元素
  • getElement(方法):獲取當前位置上的元素
  • find(方法) :在列表中查找一個元素
  • insert(方法) :在現有元素後插入新元素
  • append(方法):在列表末尾插入新元素
  • remove(方法):從列表刪除元素
  • front(方法):將列表的當前位置移動到第一個元素
  • end(方法):將列表的當前位置移動到最後一個元素
  • prev(方法) :將當前位置向前移動一位
  • next(方法):將當前位置向後移動一位
  • moveTo(方法):將當前位置移動到指定位置

3.JS代碼實現一個列表類

咱們先定義一個列表類,將列表的屬性和方法包裝在類裏函數

function List(){
    this.dataSet = []//初始化一個空數組來保存列表元素
    this.pos = 0//初始化一個屬性表示列表當前的位置
    this.listSize = 0 //初始化一個屬性表示列表元素個數
    this.clear = clear;//清空列表裏的元素
    this.find = find;//在列表上查找一個元素
    this.getElement = getElement;//返回當前位置的元素
    this.toString = toString;//將列表做爲字符串展現
    this.insert = insert;//在當前元素後插入新元素
    this.append = append;//在列表末尾插入新元素
    this.remove = remove;//從列表中刪除元素
    this.front = front;//將當前位置移到列表頭部
    this.end = end;//將當前位置移到最後一個元素
    this.prev = prev;
    this.next = next
    this.currPos = currPos;
    this.moveTo = moveTo;
    this.contains = contains;
}

有了這個類,咱們就能夠執果索因,一步步將完整的構造函數寫出來this

3.1 實現clear 方法

function clear(){
    delete this.dataSet;//刪除原來的dataSet
    this.dataSet = [];//將新數組賦給dataSet
    this.pos = this.listSize = 0;//將數組當前位置和數組長度初始化爲0
}

3.2 實現find 方法

function find(element){
    for(var i=0;i<this.dataSet.length;i++){
        if(this.dataSet[i]===element){
            return i //若找到了element,則返回該元素的位置
        }
    }
    return -1 //若沒有在dataSet中找到element,則返回-1

}

3.3 實現getElement 方法

function getElement(pos){
    return this.dataSet[this.pos]
}

3.4 實現toString 方法

function toString(){
    return this.dataSet
}

3.5 實現insert 方法

function insert(element){
    this.dataSet.splice(this.pos,0,element);
}

3.6 實現append 方法

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

3.7 實現remove方法

function remove(element){
    var nowPos = this.find(element);
    if(nowPos>-1){
        this.dataSet.splice(nowPos,1)
        this.listSize—-; //刪除元素後要把listSize也減一
        return true //刪除成功,則返回true
    }
    return false //若刪除不成功,則返回false
}

3.8 實現六個操做position的方法

function front(){
    this.pos = 0;
}

function end(){
    this.pos = this.listSize-1
}
function prev(){
    if(this.pos>0){
        this.pos—-
    }
}

function next(){
    if(this.pos<this.listSize-1){
        this.pos++
    }
}

function currPos(){
    return this.pos
}

function moveTo(newPos){
    if(newPos>=0&&newPos<=this.listSize-1){
        this.pos = newPos
    }
}

3.9 實現contains方法

function contains(element){
    var res = this.find(element);
    if(res>-1){
        return true
    }else{
        return false
    }
}
相關文章
相關標籤/搜索