javascript 数组 [ ] array
javascript 数组
javascript 数组
在JavaScript中,数组是一种特殊的对象,用于在单个变量中存储多个值。以下是一些常见的数组操作和方法:
-
创建数组:
-
访问数组元素:
-
更新数组元素:
-
添加元素到数组:
-
从数组中删除元素:
-
数组长度:
-
遍历数组:
-
数组转换为字符串:
-
数组排序:
-
数组反转:
-
创建数组:
-
数组过滤:
-
使用索引找到元素的位置:
-
使用
splice
方法添加或删除数组中的元素:
-
使用
slice
方法获取数组的一部分:
这些是JavaScript数组操作的基本方法。根据需求,你可以使用更多的方法和技巧。
====================================
splice函数
Syntax
array.splice(start, deleteCount, item1, item2, ...);
start: The index at which to start changing the array.
deleteCount: The number of elements to remove from the array.
item1, item2, ...: The elements to add to the array, starting from the start index.
Examples
Removing Elements
let fruits = ["Apple", "Banana", "Cherry", "Date"]; fruits.splice(1, 2); // Removes 2 elements starting from index 1 console.log(fruits); // Output: ["Apple", "Date"]
Adding Elements
let fruits = ["Apple", "Banana", "Cherry"]; fruits.splice(1, 0, "Blueberry", "Cranberry"); // Adds elements at index 1 console.log(fruits); // Output: ["Apple", "Blueberry", "Cranberry", "Banana", "Cherry"]
Replacing Elements
let fruits = ["Apple", "Banana", "Cherry"]; fruits.splice(1, 1, "Blueberry"); // Replaces 1 element at index 1 console.log(fruits); // Output: ["Apple", "Blueberry", "Cherry"]
====================================
二维数组
在JavaScript中,二维数组是一种数组,其元素本身也是数组。这允许你存储矩阵或表格形式的数据,其中每个子数组可以具有不同的长度。下面是如何创建、访问和操作二维数组的几种方法。
1. 创建二维数组
方法1:直接初始化
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
方法2:使用循环
如果你想要创建一个具有特定行数和列数的二维数组,可以使用循环:
let rows = 3;
let cols = 3;
let matrix = [];
for (let i = 0; i < rows; i++) {
matrix[i] = [];
for (let j = 0; j < cols; j++) {
matrix[i][j] = 0; // 或者其他初始值
}
}
2. 访问二维数组的元素
要访问二维数组中的元素,你需要指定行索引和列索引:
let value = matrix[1][2]; // 访问第2行第3列的元素,结果是6
3. 修改二维数组的元素
修改元素和访问元素的方式相同:
matrix[1][2] = 10; // 将第2行第3列的元素改为10
4. 遍历二维数组
遍历二维数组通常需要两层循环:外层循环遍历行,内层循环遍历列。
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
console.log(matrix[i][j]); // 打印每个元素的值
}
}
5. 使用Array.map()和Array.forEach()方法
虽然这些方法通常用于一维数组,但你也可以使用它们来操作二维数组。例如,使用map()来创建一个新数组,其中每个元素都是原数组中对应元素的平方:
let matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
let squaredMatrix = matrix.map(row => row.map(cell => cell * cell)); // [[1, 4, 9], [16, 25, 36], [49, 64, 81]]
====================================