当前位置:首页 > JavaScript

js列表实现增删查改

2026-03-01 20:50:11JavaScript

使用数组实现列表操作

JavaScript中数组(Array)是最常用的列表结构,以下是基于数组的增删查改实现方法:

初始化列表

let list = [1, 2, 3, 4]; // 基础初始化
let list2 = new Array(); // 空数组

增加元素

// 末尾添加
list.push(5); // [1,2,3,4,5]

// 开头添加
list.unshift(0); // [0,1,2,3,4,5]

// 指定位置插入
list.splice(2, 0, 'new'); // [0,1,'new',2,3,4,5]

删除元素

// 末尾删除
list.pop(); // 返回5,列表变为[0,1,'new',2,3,4]

// 开头删除
list.shift(); // 返回0,列表变为[1,'new',2,3,4]

// 指定位置删除
list.splice(1, 1); // 删除index=1的元素,返回['new'],列表变为[1,2,3,4]

查询元素

// 按索引查询
let item = list[1]; // 返回2

// 查找索引
let index = list.indexOf(3); // 返回2

// 条件查找
let found = list.find(x => x > 2); // 返回3

修改元素

// 直接索引修改
list[1] = 'updated'; // [1,'updated',3,4]

// 批量修改
list.splice(0, 2, 'a', 'b'); // 从0开始替换2个元素,列表变为['a','b',3,4]

使用链表实现列表操作

对于需要频繁插入删除的场景,可以自定义链表实现:

链表节点定义

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

链表基本操作

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

  // 添加元素
  add(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++;
  }

  // 删除元素
  remove(val) {
    if (!this.head) return false;

    if (this.head.val === val) {
      this.head = this.head.next;
      this.size--;
      return true;
    }

    let current = this.head;
    while (current.next) {
      if (current.next.val === val) {
        current.next = current.next.next;
        this.size--;
        return true;
      }
      current = current.next;
    }
    return false;
  }

  // 查找元素
  contains(val) {
    let current = this.head;
    while (current) {
      if (current.val === val) return true;
      current = current.next;
    }
    return false;
  }
}

性能比较

数组适合随机访问和尾部操作,时间复杂度:

  • 访问:O(1)
  • 搜索:O(n)
  • 插入/删除:头部O(n),尾部O(1)

链表适合频繁插入删除,时间复杂度:

  • 访问:O(n)
  • 搜索:O(n)
  • 插入/删除:已知位置时O(1)

ES6+新特性

现代JavaScript提供了更简洁的操作方式:

js列表实现增删查改

// 扩展运算符添加元素
list = [...list, 6]; 

// 过滤删除
list = list.filter(x => x !== 3);

// 映射修改
list = list.map(x => x * 2);

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

相关文章

js实现继承

js实现继承

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

js 进度条的实现

js 进度条的实现

使用 HTML 和 CSS 创建基础进度条 HTML 结构可以简单使用一个 div 元素作为容器,内部嵌套另一个 div 表示进度: <div class="progress-containe…

js防抖和节流实现

js防抖和节流实现

防抖(Debounce)的实现 防抖的核心思想是在事件被触发后,延迟执行回调函数。如果在延迟时间内再次触发事件,则重新计时。适用于输入框搜索、窗口大小调整等场景。 function debounce…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

vue实现文本列表

vue实现文本列表

Vue 实现文本列表的方法 Vue 可以通过多种方式实现文本列表的渲染和管理,以下是几种常见的方法: 使用 v-for 指令渲染列表 通过 v-for 指令可以动态渲染数组或对象中的文本列表。 &…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…