当前位置:首页 > JavaScript

js实现arraylist

2026-03-13 21:35:04JavaScript

在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数组已具备大多数集合操作功能,包括:

js实现arraylist

  • map()/filter() 数据转换
  • find()/includes() 元素查找
  • slice() 子数组获取
  • concat() 数组合并

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

标签: jsarraylist
分享给朋友:

相关文章

js实现图片放大缩小

js实现图片放大缩小

实现图片放大缩小的基础方法 使用CSS的transform: scale()属性可以快速实现图片的放大缩小效果。通过JavaScript动态修改该属性值: const img = document.…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

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 jquery

js jquery

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画设计和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够…

js实现选题

js实现选题

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