当前位置:首页 > JavaScript

js列表实现增删查改

2026-04-04 21:37:19JavaScript

使用数组实现增删查改

JavaScript中数组(Array)是最常用的列表结构,以下是基于数组的增删查改操作示例:

初始化数组

let list = [1, 2, 3, 4];

增加元素

// 末尾添加
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(); // [0, 1, 'new', 2, 3, 4]

// 开头删除
list.shift(); // [1, 'new', 2, 3, 4]

// 指定位置删除
list.splice(1, 1); // [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 = list.map(x => x * 2); // [2, 'updatedupdated', 6, 8]

使用链表实现增删查改

如需实现链表结构,需先定义节点类:

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

初始化链表

let head = new ListNode(1, new ListNode(2, new ListNode(3)));

增加节点

// 头部插入
head = new ListNode(0, head);

// 尾部插入
let current = head;
while (current.next) current = current.next;
current.next = new ListNode(4);

// 指定位置插入
let pos = 1;
current = head;
for (let i = 0; i < pos - 1; i++) current = current.next;
current.next = new ListNode('new', current.next);

删除节点

// 头部删除
head = head.next;

// 尾部删除
current = head;
while (current.next.next) current = current.next;
current.next = null;

// 指定位置删除
pos = 2;
current = head;
for (let i = 0; i < pos - 1; i++) current = current.next;
current.next = current.next.next;

查询节点

// 按索引查询
pos = 1;
current = head;
for (let i = 0; i < pos; i++) current = current.next;
let nodeVal = current.val;

// 按值查询
current = head;
while (current && current.val !== 3) current = current.next;
let targetNode = current;

修改节点

// 直接修改值
pos = 1;
current = head;
for (let i = 0; i < pos; i++) current = current.next;
current.val = 'updated';

性能对比

  • 数组:随机访问O(1),插入/删除头部O(n),插入/删除尾部O(1)/O(1)
  • 链表:随机访问O(n),插入/删除头部O(1),插入/删除尾部O(n)

根据需求选择数据结构:

js列表实现增删查改

  • 频繁随机访问 → 数组
  • 频繁插入删除 → 链表

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

相关文章

js实现倒计时

js实现倒计时

实现倒计时的基本方法 使用 JavaScript 实现倒计时功能可以通过 setInterval 或 setTimeout 结合日期计算来完成。以下是几种常见的实现方式: 使用 setInterva…

vue实现列表循环

vue实现列表循环

列表循环的实现方式 在Vue中实现列表循环主要依赖于v-for指令,该指令基于源数据多次渲染元素或模板块。 基础数组循环 使用v-for遍历数组时,语法为item in items或(item, i…

js实现选题

js实现选题

实现选题功能的JavaScript方法 基础实现方案 使用数组存储选项,通过随机索引选取: const options = ['选项A', '选项B', '选项C', '选项D']; const r…

js实现下拉刷新

js实现下拉刷新

监听触摸事件 通过监听 touchstart、touchmove 和 touchend 事件来检测用户下拉手势。记录触摸起始位置和移动距离。 let startY = 0; let curr…

js实现复制功能实现

js实现复制功能实现

使用document.execCommand方法(传统方式,已逐渐被弃用) 传统方式通过document.execCommand('copy')实现复制功能,需先选中文本。以下是一个完整示例: fu…

js实现截图

js实现截图

使用HTML2Canvas库实现截图 HTML2Canvas是一个流行的JavaScript库,可以将网页元素或整个页面转换为Canvas图像。安装方式: npm install html2canv…