您现在的位置是:网站首页 > 数组基本操作(增删改查)文章详情

数组基本操作(增删改查)

数组是JavaScript中最常用的数据结构之一,对数组的增删改查操作是日常开发中的基础技能。下面详细展开这些操作的具体实现方式和应用场景。

数组的创建与初始化

创建数组有两种基本方式:

// 字面量方式
const arr1 = [1, 2, 3];

// 构造函数方式
const arr2 = new Array(1, 2, 3);

初始化特定长度的空数组:

const emptyArray = new Array(5); // 创建长度为5的空数组

ES6新增的Array.of()方法可以避免构造函数参数歧义:

Array.of(7); // [7] 
new Array(7); // [empty × 7]

添加元素

末尾添加

const fruits = ['apple', 'banana'];
fruits.push('orange'); // ['apple', 'banana', 'orange']

开头添加

fruits.unshift('pear'); // ['pear', 'apple', 'banana', 'orange']

指定位置插入

使用splice方法:

fruits.splice(2, 0, 'grape'); 
// 参数:起始索引、删除数量、插入元素
// ['pear', 'apple', 'grape', 'banana', 'orange']

数组合并

const newFruits = fruits.concat(['melon', 'kiwi']);
// 原数组不变,返回新数组

ES6扩展运算符:

const combined = [...fruits, ...['melon', 'kiwi']];

删除元素

末尾删除

fruits.pop(); // 返回'orange',数组变为['pear', 'apple', 'grape', 'banana']

开头删除

fruits.shift(); // 返回'pear',数组变为['apple', 'grape', 'banana']

指定位置删除

fruits.splice(1, 1); // 从索引1开始删除1个元素
// 返回['grape'],数组变为['apple', 'banana']

清空数组

fruits.length = 0; // 最快速清空方式

修改元素

直接索引修改

fruits[0] = 'pineapple'; // ['pineapple', 'banana']

批量修改

fruits.splice(0, 2, 'mango', 'peach'); 
// 从0开始替换2个元素
// ['mango', 'peach']

填充数组

const nums = [1, 2, 3];
nums.fill(0, 1, 3); // 用0填充索引1到3
// [1, 0, 0]

查询元素

基本查询

fruits.indexOf('banana'); // 返回索引,不存在返回-1
fruits.includes('apple'); // 返回布尔值

条件查询

const numbers = [1, 4, 9, 16];
numbers.find(n => n > 5); // 9
numbers.findIndex(n => n > 5); // 2

筛选数组

const bigNumbers = numbers.filter(n => n > 5);
// [9, 16]

检查元素

numbers.every(n => n < 20); // true
numbers.some(n => n > 10); // true

高级操作方法

数组映射

const squares = numbers.map(n => n * n);
// [1, 16, 81, 256]

数组排序

const unsorted = [3, 1, 4, 2];
unsorted.sort((a, b) => a - b); // [1, 2, 3, 4]

数组反转

numbers.reverse(); // [16, 9, 4, 1]

数组拼接

const partial = numbers.slice(1, 3); // [9, 4]
// 原数组不变

数组降维

const nested = [1, [2, 3], [4, [5]]];
nested.flat(2); // [1, 2, 3, 4, 5]

性能考虑

大规模数据操作时需要注意:

  • push/pop比shift/unshift快得多
  • 连续操作可先用concat合并再一次性赋值
  • 查询优先使用includes而不是indexOf
  • 避免在循环中直接修改数组长度
// 低效做法
for(let i = 0; i < arr.length; i++) {
  arr.pop();
}

// 高效做法
arr.length = 0;

实际应用示例

实现一个待办事项列表的基本操作:

class TodoList {
  constructor() {
    this.todos = [];
  }

  add(todo) {
    this.todos.push(todo);
  }

  removeById(id) {
    this.todos = this.todos.filter(todo => todo.id !== id);
  }

  update(id, newText) {
    const todo = this.todos.find(t => t.id === id);
    if(todo) todo.text = newText;
  }

  search(keyword) {
    return this.todos.filter(todo => 
      todo.text.includes(keyword)
    );
  }
}

我的名片

网名:~川~

岗位:console.log 调试员

坐标:重庆市-九龙坡区

邮箱:cc@qdcc.cn

沙漏人生

站点信息

  • 建站时间:2013/03/16
  • 本站运行
  • 文章数量
  • 总访问量
微信公众号
每次关注
都是向财富自由迈进的一步