class List {
|
constructor () {
|
this.dataSouce = []
|
}
|
|
add (index, element) {
|
if (!index) {
|
this.addEnd(element)
|
} else if (index >= this.dataSouce.length) {
|
this.addEnd(element)
|
} else if (index === 1) {
|
this.addFront(element)
|
} else {
|
this._add(index, element)
|
}
|
}
|
|
/**
|
* 在列表的末尾添加新元素
|
* @param {*} element 要添加的元素
|
*/
|
addEnd (element) {
|
this.dataSouce[this.dataSouce.length] = element
|
}
|
|
/**
|
* 在列表头部添加新元素
|
* @param {*} element
|
* @param {*} after
|
*/
|
addFront (element) {
|
this._add(0, element)
|
}
|
|
_add (index, element) {
|
const newArr = []
|
for (var i = this.dataSouce.length - 1; i > index - 1; i--) {
|
newArr[i + 1] = this.dataSouce[i]
|
}
|
newArr[index] = element
|
this.dataSouce = newArr
|
}
|
|
/**
|
* 在列表中移除一个元素
|
* @param {*} element 要删除的元素
|
*/
|
remove (element) {
|
// 查找当前元素的索引
|
const index = this.dataSouce.indexOf(element)
|
if (index >= 0) {
|
this.dataSouce.splice(index, 1)
|
return true
|
}
|
return false
|
}
|
|
/**
|
* 判断给定的值是否在列表中
|
*/
|
contains (element) {
|
return this.dataSouce.indexOf(element) > -1
|
}
|
|
/**
|
* 清楚列表中的元素
|
*/
|
clear () {
|
delete this.dataSouce
|
this.dataSouce = []
|
}
|
|
/**
|
* 列表的长度
|
*/
|
length () {
|
return this.dataSouce.length
|
}
|
|
join (comma) {
|
this.removeBlank()
|
return this.dataSouce.join(comma)
|
}
|
|
removeBlank () {
|
const arr = this.dataSouce
|
console.log(arr)
|
for (const k in arr) {
|
if (!arr[k]) {
|
this.dataSouce.splice(k, 1)
|
}
|
}
|
}
|
}
|
|
export default List
|