列表是一組有序數據的集合,其中的每項數據被稱爲 元素
。在js中,列表中的元素能夠是任意數據類型。列表中能夠保存任意多個元素(在實際使用時會受到程序內存的限制)。數組
列表中有一些常見的屬性和方法,下面一一列舉:app
咱們先定義一個列表類,將列表的屬性和方法包裝在類裏函數
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
function clear(){ delete this.dataSet;//刪除原來的dataSet this.dataSet = [];//將新數組賦給dataSet this.pos = this.listSize = 0;//將數組當前位置和數組長度初始化爲0 }
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 }
function getElement(pos){ return this.dataSet[this.pos] }
function toString(){ return this.dataSet }
function insert(element){ this.dataSet.splice(this.pos,0,element); }
function append(element){ this.dataSet[this.listSize++]=element; }
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 }
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 } }
function contains(element){ var res = this.find(element); if(res>-1){ return true }else{ return false } }