当前位置:首页 > JavaScript

js 列表实现

2026-02-02 02:49:05JavaScript

JavaScript 列表实现方法

在 JavaScript 中,列表通常通过数组或特定数据结构实现。以下是几种常见的实现方式:

使用原生数组

JavaScript 数组自带多种列表操作方法,适合大多数场景:

js 列表实现

const list = [1, 2, 3];
list.push(4); // 尾部添加
list.pop();   // 尾部移除
list.unshift(0); // 头部添加
list.shift();    // 头部移除

链表实现

需要更灵活的操作时可实现链表结构:

js 列表实现

class ListNode {
  constructor(val) {
    this.val = val;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.size = 0;
  }

  addAtTail(val) {
    const node = new ListNode(val);
    if (!this.head) this.head = node;
    else {
      let current = this.head;
      while (current.next) current = current.next;
      current.next = node;
    }
    this.size++;
  }
}

双向链表实现

需要双向遍历时可扩展为双向链表:

class DoublyListNode {
  constructor(val) {
    this.val = val;
    this.prev = null;
    this.next = null;
  }
}

class DoublyLinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    this.size = 0;
  }

  addAtTail(val) {
    const node = new DoublyListNode(val);
    if (!this.head) this.head = node;
    else {
      node.prev = this.tail;
      this.tail.next = node;
    }
    this.tail = node;
    this.size++;
  }
}

性能优化建议

  • 频繁插入/删除操作时优先考虑链表结构
  • 随机访问需求高时使用原生数组
  • 大数据量时注意链表的内存开销

实用工具方法

扩展数组功能实现类 List 操作:

class List {
  constructor(items = []) {
    this.items = [...items];
  }

  add(item) {
    this.items.push(item);
  }

  remove(index) {
    return this.items.splice(index, 1)[0];
  }

  get(index) {
    return this.items[index];
  }
}

标签: 列表js
分享给朋友:

相关文章

js实现日历

js实现日历

实现日历的基本思路 使用JavaScript实现日历的核心是动态生成日期表格,并处理月份切换逻辑。需要计算当前月的天数、起始星期几,并动态渲染到页面上。 获取当前日期信息 通过Date对象获取当前年…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js如何实现继承

js如何实现继承

原型链继承 通过将子类的原型指向父类的实例实现继承。子类实例能够访问父类原型上的属性和方法。 function Parent() { this.name = 'parent'; } Parent…

js实现列表

js实现列表

使用 JavaScript 实现列表 JavaScript 提供了多种方式来实现列表功能,包括数组操作、DOM 元素动态生成等。以下是几种常见的实现方法: 使用数组存储列表数据 数组是 JavaSc…

js实现延迟

js实现延迟

实现延迟的方法 在JavaScript中,实现延迟操作有多种方式,以下是几种常见的方法: 使用setTimeout函数 setTimeout是JavaScript中最常用的延迟执行方法。它接受一个…

js实现图表

js实现图表

在JavaScript中实现图表通常使用流行的图表库,以下是几种常见的方法和工具: 使用Chart.js Chart.js是一个简单灵活的库,适合快速生成响应式图表。安装方式包括CDN引入或npm安…