构建通用方法去实现增删改查以及遍历。这是一个思想,可以借鉴一下。
function List() {
this.listSize = 0// 列表元素个数
this.pos = 0
this.dataSource = []
this.append = append
this.remove = remove
this.find = find
this.toString = toString
this.clear = clear
this.insert = insert
this.front = front
this.end = end
this.prev = prev
this.next = next
this.length = length
this.currPos = currPos
this.moveTo = moveTo
this.getElement = getElement
this.length = length
this.contains = contains
}
function append(element) {
this.dataSource[this.listSize] = element
this.listSize += 1
}
function find(element) {
for (let i = 0; i < this.dataSource.length; ++i) {
if (this.dataSource[i] === element) {
return i
}
return -1
}
}
function remove(element) {
console.log(this)
var foundAt = this.find(element)
// 先找到对应的位置,然后用splice删除,同时将长度-1
if (foundAt > -1) {
this.dataSource.splice(foundAt, 1)
this.listSize -= 1
return true
}
return false
}
function length() {
return this.listSize
}
function toString() {
return this.dataSource
}
function insert(element, after) {
var insertPos = this.find(after)
if (insertPos > -1) {
this.dataSource.splice(insertPos + 1, 0, element)
++this.listSize
return true
}
return false
}
function clear() {
delete this.dataSource
this.dataSource = []
this.listSize = 0
this.pos = 0
}
function contains(element) {
for (let i = 0; i < this.dataSource.length; ++i) {
if (this.dataSource[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() {
return this.pos
}
function moveTo(position) {
this.pos = position
}
function getElement() {
return this.dataSource[this.pos]
}
var listFun = new List()
listFun.append('&&')
console.log(listFun.toString)
listFun.remove('&&')
listFun.append('&2&')
listFun.append('2&2&')
listFun.append('22')
listFun.front()
console.log(listFun.getElement())
listFun.next()
console.log(listFun.getElement())
listFun.next()
listFun.next()
listFun.prev()
console.log(listFun.getElement())
// 你看用自己写的方法,完成遍历
for (listFun.front(); listFun.currPos() < listFun.length(); listFun.next()) {
console.log(listFun.getElement())
}
// 倒序的遍历
for (listFun.end(); listFun.currPos() >= 0; listFun.prev()) {
console.log(listFun.getElement())
}
网友评论