1. // 列表
    2. function List() {
    3. this.listSize = 0; // 列表元素个数
    4. this.pos = 0; // 列表当前位置
    5. this.dataStore = []; // 列表
    6. this.clear = clear; // 清空列表
    7. this.find = find; // 查找
    8. this.toString = toString;
    9. this.insert = insert; // 指定位置插入
    10. this.append = append; // 追加
    11. this.remove = remove; // 移除
    12. this.front = front; // 指针移到首部
    13. this.end = end; // 指针移到尾部
    14. this.prev = prev; // 前移一位
    15. this.next = next; // 后移一位
    16. this.length = listLength; // 列表长度
    17. this.currPos = currPos; // 当前指针位置
    18. // this.moveTo = moveTo;
    19. this.getElement = getElement; // 获取当前位置的元素
    20. this.contains = contains; // 查询是否包含某元素
    21. }
    22. function append(element) {
    23. this.dataStore[this.listSize++] = element;
    24. }
    25. function find(element) {
    26. for(let i = 0; i< this.listSize; i++) {
    27. if (this.dataStore[i] === element) {
    28. return i;
    29. }
    30. }
    31. return -1;
    32. }
    33. function remove(element) {
    34. var findIndex = this.find(element);
    35. if (findIndex > -1) {
    36. this.dataStore.slice(findIndex, 1);
    37. --this.listSize;
    38. return;
    39. }
    40. return false;
    41. }
    42. function listLength() {
    43. return this.listSize;
    44. }
    45. function toString() {
    46. return this.dataStore;
    47. }
    48. function insert(element, after) {
    49. var insertPos = this.find(after);
    50. if (insertPos > -1) {
    51. this.dataStore.splice(insertPos + 1, 0, element);
    52. ++this.listSize;
    53. return true;
    54. }
    55. return false;
    56. }
    57. function clear() {
    58. delete this.dataStore;
    59. this.dataStore.length = 0;
    60. this.listSize = 0;
    61. }
    62. function contains(element) {
    63. for(let i = 0; i< this.listSize; i++) {
    64. if (this.dataStore[i] === element) {
    65. return true;
    66. }
    67. }
    68. return false;
    69. }
    70. function front() {
    71. this.pos = 0;
    72. }
    73. function end() {
    74. this.pos = this.listSize - 1;
    75. }
    76. function prev() {
    77. if (this.pos > 0) {
    78. --this.pos;
    79. }
    80. }
    81. function next() {
    82. if (this.pos < this.listSize) {
    83. ++this.pos;
    84. }
    85. }
    86. function currPos() {
    87. return this.pos;
    88. }
    89. function getElement() {
    90. return this.dataStore[this.pos];
    91. }
    92. var names = new List();
    93. names.append('小红');
    94. names.append('小王');
    95. names.append('小李');
    96. names.next();
    97. // 获取当前指针元素
    98. console.log(names.getElement())
    99. // 遍历列表
    100. for(names.front();names.currPos() < names.listSize; names.next()) {
    101. console.log(names.getElement())
    102. }