(一)列表的操作
(二)实现列表类(利用数组实现)
class List {
constructor() {
this.pos = 0 // 列表当前位置
this.dataList = [] // 列表数组 初始化为空
}
// 清空列表中所有元素
clear () {
this.dataList = []
this.pos = 0
}
// 在列表中查找某一元素 找到返回索引 没找到返回-1
find (value) {
for (var i = 0; i < this.dataList.length; i++) {
if (value === this.dataList[i]) {
return i
}
}
return -1
}
// 返回列表
getList () {
return this.dataList
}
// 插入 把value插入到index位置
insert (value, index) {
if (index <= this.dataList.length) {
this.dataList.splice(index, 0, value)
return true
}
return false
}
// 列表末尾插入元素
append (value) {
this.dataList.push(value)
}
// 删除列表元素 删除成功返回true 否则返回false
remove (value) {
var index = this.find(value) // 先判断存不存在
if (index > -1) {
this.dataList.splice(index, 1)
return true
}
return false
}
// 将列表当前位置移动到第一个元素
front () {
this.pos = 0
}
// 列表中有多少元素
length () {
return this.dataList.length
}
// 将列表当前位置移动到第一个元素
end () {
this.pos = this.dataList.length - 1
}
// 当前位置前移一位
prev () {
if (this.pos > 0) {
--this.pos
}
}
// 当前位置后移一位
next () {
if (this.pos < this.dataList.length-1) {
++this.pos
}
}
// 判断是否有前一位
hasPrev () {
return this.pos > 0
}
// 判断是否有后一位
hasNext () {
return this.pos < this.dataList.length
}
// 返回列表的当前位置
currPos () {
return this.pos
}
// 当前位置移动到指定位置
moveTo (index) {
this.pos = index
}
// 获取当前位置的元素
getElement () {
return this.dataList[this.pos]
}
}
var names = new List()
names.append('Cynthia')
names.append('Raymond')
names.append('Barbara')
console.log(names.getList()) // ["Cynthia", "Raymond", "Barbara"]
names.remove('Raymond')
names.insert('Raymond', 2)
console.log(names.getList()) // ["Cynthia", "Barbara"]
names.front()
console.log(names.getElement()) // Cynthia
names.next()
names.prev()
console.log(names.hasNext())
console.log(names.hasPrev())
console.log(names.getElement()) // Cynthia