js实现arraylist
在JavaScript中,没有内置的ArrayList数据结构,但可以通过数组或自定义类模拟类似功能。以下是几种实现方式:
使用原生数组
JavaScript数组天然支持动态扩容和常用操作方法,可直接替代ArrayList:

const list = []; // 初始化
list.push(1, 2); // 添加元素
list.splice(1, 0, 99); // 在索引1插入元素
const element = list.pop(); // 移除并返回最后一个元素
list.length; // 获取当前元素数量
自定义ArrayList类
通过类封装数组实现更接近Java ArrayList的功能:
class ArrayList {
constructor() {
this.items = [];
}
add(element) {
this.items.push(element);
}
insert(index, element) {
this.items.splice(index, 0, element);
}
remove(index) {
return this.items.splice(index, 1)[0];
}
get(index) {
return this.items[index];
}
size() {
return this.items.length;
}
clear() {
this.items = [];
}
}
// 使用示例
const myList = new ArrayList();
myList.add('a');
myList.insert(0, 'b');
console.log(myList.get(1)); // 输出 'a'
性能优化实现
针对大规模数据操作,可预分配内存空间:

class OptimizedArrayList {
constructor(initialCapacity = 10) {
this.capacity = initialCapacity;
this.items = new Array(initialCapacity);
this.length = 0;
}
_resize() {
this.capacity *= 2;
const newItems = new Array(this.capacity);
for (let i = 0; i < this.length; i++) {
newItems[i] = this.items[i];
}
this.items = newItems;
}
add(element) {
if (this.length === this.capacity) {
this._resize();
}
this.items[this.length++] = element;
}
}
类型安全的TS实现
使用TypeScript可添加类型约束:
class TypedArrayList<T> {
private items: T[];
constructor() {
this.items = [];
}
add(item: T): void {
this.items.push(item);
}
get(index: number): T {
return this.items[index];
}
}
// 使用示例
const numberList = new TypedArrayList<number>();
numberList.add(42);
JavaScript数组已具备大多数集合操作功能,包括:
map()/filter()数据转换find()/includes()元素查找slice()子数组获取concat()数组合并
对于需要特定功能的场景,选择原生数组或自定义类均可满足需求。






