在 JavaScript 中,数组是一种有序的元素集合,每个元素都可以通过索引(从 0 开始)进行访问。以下是定义和使用数组的详细说明:
1. 定义数组使用方括号 [] 或 Array 构造函数定义数组,推荐使用字面量语法([]),因为它更简洁高效。
// 使用字面量语法(推荐)const array1 = [1, 2, 3]; // 数字数组const array2 = ["a"罩慧棚, "b", "c"]; // 字符串数组const array3 = [true, false, null]; // 混合类型数组const array4 = []; // 空数组// 使用 Array 构造函数(不推荐)const array5 = new Array(1, 2, 3); // 等效于 array1const array6 = new Array(5); // 创建长度为5的空数组(非推荐用法)2. 访问数组元素通过索引(从 0 开始)访问或修改元素:
const fruits = ["apple", "banana", "cherry"];console.log(fruits[0]); // 输出 "apple"fruits[1] = "blueberry"; // 修改第二个元素console.log(fruits); // 输出 ["apple", "blueberry", "cherry"]3. 常用数组方法添加/删除元素- push():在末尾添加元素。fruits.push("orange"); // ["apple", "blueberry", "cherry", "orange"]
- pop():删除末尾元素。fruits.pop(); // 返回 "orange",数组变为 ["apple", "blueberry", "cherry"]
- shift():删除开头元素。fruits.shift(); // 返回 "apple",数组变为 ["blueberry", "cherry"]
- unshift():在开头添加元素。fruits.unshift("kiwi"); // ["kiwi", "blueberry", "cherry"]
插入/删除/替换元素- splice(startIndex, deleteCount, ...items):const colors = ["red", "green", "blue"];colors.splice(1, 1, "yellow", "purple"); // 从索引1删除1个元素,插入新元素console.log(colors); // ["red", "yellow", "purple", "blue"]
其他常用方法- slice(start, end):截取子数组(不修改原数组)。const subColors = colors.slice(1, 3); // ["yellow", "purple"]
- concat():合并数组。const combined = colors.concat(["black", "white"]);
- join(separator):将数组转为字符串。console.log(colors.join(", ")); // "red, yellow, purple, blue"
4. 注意事项- 数组是对象:JavaScript 数组是特殊类型的对象,可以动态调整长度。碧隐const dynamicArray = [];dynamicArray[10] = "test"; // 长度自动变为11(索引0-9为empty)物则
- 稀疏数组:未赋值的索引会生成空位(empty),可能影响某些方法的行为。const sparse = [1, , 3]; // 第二个元素是 emptyconsole.log(sparse.length); // 3
5. 示例总结// 定义数组const numbers = [10, 20, 30];// 操作数组numbers.push(40); // [10, 20, 30, 40]numbers.splice(1, 2, 15); // [10, 15, 40]// 访问元素console.log(numbers[0]); // 10通过以上方法,可以灵活地定义、访问和操作 JavaScript 数组。