当前位置:首页 > JavaScript

js 列表实现

2026-02-02 02:49:05JavaScript

JavaScript 列表实现方法

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

使用原生数组

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

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

链表实现

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

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 操作:

js 列表实现

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实现验证码

使用Canvas生成图形验证码 在HTML中创建一个Canvas元素用于绘制验证码。通过JavaScript随机生成数字或字母组合,并添加干扰线、噪点等干扰元素增强安全性。 <canvas i…

jquery.js

jquery.js

jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互等操作。以下是关于 jQuery.js 的核心信息和使用方法: 获…

js实现类

js实现类

JavaScript 实现类的几种方式 JavaScript 是一种基于原型的语言,但在 ES6 之后引入了 class 语法糖,使得实现类更加直观。以下是几种常见的实现方式: 使用构造函数 传统的…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

vue实现功能列表

vue实现功能列表

Vue 实现功能列表的方法 在 Vue 中实现功能列表通常涉及数据绑定、列表渲染、事件处理和状态管理。以下是几种常见的方法: 数据驱动列表渲染 使用 v-for 指令可以轻松实现列表渲染。假设有一个…