当前位置:首页 > JavaScript

js实现arraylist

2026-03-13 21:35:04JavaScript

在JavaScript中,没有内置的ArrayList数据结构,但可以通过数组或自定义类模拟类似功能。以下是几种实现方式:

使用原生数组

JavaScript数组天然支持动态扩容和常用操作方法,可直接替代ArrayList

js实现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'

性能优化实现

针对大规模数据操作,可预分配内存空间:

js实现arraylist

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() 数组合并

对于需要特定功能的场景,选择原生数组或自定义类均可满足需求。

标签: jsarraylist
分享给朋友:

相关文章

js实现轮播

js实现轮播

实现轮播图的基本思路 轮播图的核心逻辑是通过定时切换展示的图片或内容,通常结合左右滑动按钮和指示器(小圆点)增强交互性。以下是基于原生JavaScript的实现方法。 HTML结构 构建轮播图的HT…

js实现拷贝

js实现拷贝

实现文本拷贝 使用 document.execCommand 方法(已废弃但兼容性较好): function copyText(text) { const textarea = document…

js分组实现

js分组实现

分组实现方法 在JavaScript中,可以通过多种方式实现数组或对象的分组操作。以下是几种常见的方法: 使用Array.prototype.reduce() 通过reduce方法可以轻松实现数组分…

js实现vr

js实现vr

使用WebXR API实现VR体验 WebXR是浏览器中实现VR和AR体验的标准API,它取代了早期的WebVR。现代浏览器如Chrome、Edge和Firefox已支持WebXR。 // 初始化W…

js类实现

js类实现

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

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…