JavaScript 数组基本操作笔记

发布于 2025-02-05  248 次阅读


JavaScript 数组基本操作笔记

在JavaScript中,数组是一种特殊的变量,能够同时存储多个值。这些值可以是任何数据类型,并且数组的大小是可变的。以下是JavaScript数组的一些基本操作及其用法。

1. 创建数组

使用数组字面量

let fruits = ["Apple", "Banana", "Orange"];

使用Array构造函数

let numbers = new Array(1, 2, 3, 4, 5);

或者指定数组长度(不推荐用于初始化具有具体值的数组)

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

2. 访问数组元素

通过索引访问数组元素,索引从0开始。

let fruits = ["Apple", "Banana", "Orange"];
console.log(fruits[0]); // 输出: Apple

3. 修改数组元素

直接通过索引赋值修改数组元素。

fruits[1] = "Blueberry";
console.log(fruits); // 输出: ["Apple", "Blueberry", "Orange"]

4. 添加数组元素

在末尾添加元素(使用push方法)

fruits.push("Grape");
console.log(fruits); // 输出: ["Apple", "Blueberry", "Orange", "Grape"]

在指定位置添加元素(使用splice方法)

fruits.splice(1, 0, "Strawberry"); // 在索引1的位置插入"Strawberry"
console.log(fruits); // 输出: ["Apple", "Strawberry", "Blueberry", "Orange", "Grape"]

注意:splice方法不仅可以添加元素,还可以删除和替换元素。

5. 删除数组元素

使用pop方法删除末尾元素

fruits.pop();
console.log(fruits); // 输出: ["Apple", "Strawberry", "Blueberry", "Orange"]

使用splice方法删除指定位置的元素

fruits.splice(1, 1); // 从索引1开始删除1个元素
console.log(fruits); // 输出: ["Apple", "Blueberry", "Orange"]

6. 遍历数组

使用for循环

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

使用forEach方法

fruits.forEach(function(fruit) {
  console.log(fruit);
});

或者使用箭头函数

fruits.forEach(fruit => console.log(fruit));

7. 查找数组元素

使用indexOf方法查找元素索引

let index = fruits.indexOf("Blueberry");
console.log(index); // 输出: 1

使用includes方法检查元素是否存在

let exists = fruits.includes("Orange");
console.log(exists); // 输出: true

8. 数组长度

通过length属性获取数组长度。

console.log(fruits.length); // 输出: 3

9. 数组连接

使用concat方法连接数组

let moreFruits = ["Mango", "Papaya"];
let allFruits = fruits.concat(moreFruits);
console.log(allFruits); // 输出: ["Apple", "Blueberry", "Orange", "Mango", "Papaya"]

使用扩展运算符(ES6)

let allFruitsES6 = [...fruits, ...moreFruits];
console.log(allFruitsES6); // 输出: ["Apple", "Blueberry", "Orange", "Mango", "Papaya"]

这些基本操作涵盖了JavaScript数组的大部分常用功能,能够帮助开发者有效地处理数组数据。

下次见面会是什么时候呢?
最后更新于 2025-02-05