在 JavaScript 中,数组是一种非常常用的数据结构,用于存储和操作一系列有序的元素。以下是一些在 JavaScript 中常用的数组操作方法:
1. 创建数组:
const arr = [1, 2, 3, 4, 5];
2. 访问数组元素:
console.log(arr[0]); // 输出 1
3. 修改数组元素:
arr[0] = 10;
console.log(arr); // 输出 [10, 2, 3, 4, 5]
4. 获取数组长度:
console.log(arr.length); // 输出 5
5. 遍历数组:
arr.forEach((element, index) => {
console.log(`Element at index ${index}: ${element}`);
});
6. 添加元素到数组末尾:
arr.push(6);
console.log(arr); // 输出 [10, 2, 3, 4, 5, 6]
7. 移除数组末尾的元素:
arr.pop();
console.log(arr); // 输出 [10, 2, 3, 4, 5]
8. 添加元素到数组开头:
arr.unshift(0);
console.log(arr); // 输出 [0, 10, 2, 3, 4, 5]
9. 移除数组开头的元素:
arr.shift();
console.log(arr); // 输出 [10, 2, 3, 4, 5]
10. 截取数组的一部分:
const newArr = arr.slice(1, 4);
console.log(newArr); // 输出 [2, 3, 4]
11. 合并两个数组:
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combinedArr = arr1.concat(arr2);
console.log(combinedArr); // 输出 [1, 2, 3, 4, 5, 6]
12. 查找数组中的元素:
const index = arr.indexOf(3);
console.log(index); // 输出 2
13. 使用 map 对数组进行操作:
const doubledArr = arr.map((element) => element * 2);
console.log(doubledArr); // 输出 [20, 4, 6, 8, 10]
14. 使用 filter 筛选数组:
const evenArr = arr.filter((element) => element % 2 === 0);
console.log(evenArr); // 输出 [10, 2, 4]
15. 使用 reduce 对数组进行累计操作:
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum); // 输出 24