function List() { this.listSize = 0; 列表的元素個數 this.pos = 0; 列表的當前位置 this.dataStore = []; 列表數組 this.append = append; 列表的末尾添加新元素 this.find = find; 找到指定元素的位置 this.toString = toString; 返回列表的字符串形式 this.insert = insert; 在現有元素後插入新元素 this.remove = remove; 從列表中刪除元素 this.clear = clear; 清空列表中的全部元素 this.front = front; 將列表的當前位置移到第一個元素 this.end = end; 將列表的當前位置移到最後一個元素 this.next = next; 將當前位置後移一位 this.hasNext; 判斷是否有後一位 this.hasPrev; 判斷是否有前一位 this.length = length; 返回列表元素的個數 this.currPos = currPos; 返回列表的當前位置 this.moveTo = moveTo; 將列表的當前位置移動到指定位置 this.getElement = getElement; 返回當前位置的元素 this.contains = contains; 判斷給定元素是否在列表中 }
function append(element) { this.dataStore[this.listSize++] = element; }
function find(element) { for (let i = 0; i < this.listSize; i++) { console.log(i); if (element == this.dataStore[i]) { return i; } } return -1; }
function remove(element) { let findAt = this.find(element); if (findAt > -1) { this.dataStore.splice(findAt, 1); --this.listSize; return true; } }
function length() { return this.listSize; }
function toString() { return this.dataStore; }
function insert(element, after) { let insertAt = this.find(after); if (insertAt > -1) { this.dataStore.splice(insertAt + 1, 0, element); this.listSize++; return true; } return false; }
function clear() { delete this.dataStore; this.dataStore = []; this.listSize = this.pos = 0; }
function contains(element) { for (let i = 0; i < this.listSize; i++) { if (this.dataStore[i] == element) { return true; } } return 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() {app
return this.pos;
}函數
function moveTo(position) { if (position < this.listSize - 1) { this.pos = position; } }
function getElement() { return this.dataStore[this.pos]; }
function hasNext() { return this.pos < this.listSize - 1; }
function hasPrev() { return this.pos > 0; } //初始化一個列表 let list = new List(); list.append('jianguang'); list.append('yinjun'); list.append('jiangsssuang'); list.append('yinssjun'); 移動到第一個元素位置而且顯示 list.front(); print(list.getElement()); 移動向前一個元素位置,而且顯示 list.next(); print(list.getElement());
還能夠測試列表的其餘數據來經過列表實現想要的效果
歡迎評論以及留言,同時歡迎關注個人博客定時不斷地更新個人文章 陳建光的博客測試