js list实现
在 JavaScript 中实现列表操作
JavaScript 中的列表通常通过数组(Array)来实现,数组提供了丰富的内置方法用于操作数据。以下是一些常见的列表操作实现方式:
创建列表
const list = []; // 空列表
const numbers = [1, 2, 3]; // 包含数字的列表
const mixed = [1, 'a', true]; // 混合类型列表
添加元素
list.push(4); // 末尾添加元素,变为 [4]
list.unshift(0); // 开头添加元素,变为 [0, 4]
删除元素
list.pop(); // 移除末尾元素,返回4,列表变为 [0]
list.shift(); // 移除开头元素,返回0,列表变为 []
访问元素
const first = numbers[0]; // 获取第一个元素,值为1
numbers[1] = 'new'; // 修改第二个元素,列表变为 [1, 'new', 3]
遍历列表

numbers.forEach(item => console.log(item)); // 依次打印每个元素
const doubled = numbers.map(x => x * 2); // 生成新列表 [2, 'newnew', 6]
查找元素
const hasTwo = numbers.includes(2); // 检查是否包含2,返回false
const index = numbers.indexOf(3); // 查找元素3的位置,返回2
过滤列表
const filtered = numbers.filter(x => typeof x === 'number'); // 过滤出数字 [1, 3]
连接列表

const combined = numbers.concat([4, 5]); // 连接为新列表 [1, 'new', 3, 4, 5]
排序列表
const sorted = [3, 1, 2].sort((a, b) => a - b); // 数字排序 [1, 2, 3]
const alphaSorted = ['c', 'a', 'b'].sort(); // 字母排序 ['a', 'b', 'c']
其他实用操作
const sliced = numbers.slice(1, 3); // 切片获取 ['new', 3]
const joined = numbers.join('-'); // 拼接为字符串 "1-new-3"
const length = numbers.length; // 获取列表长度 3
实现链表数据结构
对于需要链表结构的场景,可以自定义实现:
class ListNode {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
this.tail = null;
}
append(value) {
const newNode = new ListNode(value);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
}
// 其他链表方法如prepend, delete, find等
}
const list = new LinkedList();
list.append(1);
list.append(2);
使用第三方库
对于更复杂的列表操作,可以考虑使用工具库:
- Lodash(提供丰富的数组操作方法)
- Immutable.js(提供不可变列表数据结构)
这些实现方式覆盖了JavaScript中列表操作的主要需求,从基础数组操作到自定义链表结构,开发者可以根据具体场景选择合适的方法。






