js实现数组
JavaScript 数组操作指南
创建数组
使用字面量方式创建数组是最常见的方法:
const arr1 = [1, 2, 3]; // 包含三个数字的数组
const arr2 = ['a', 'b', 'c']; // 字符串数组
const arr3 = [true, false, true]; // 布尔值数组
通过构造函数创建数组:
const arr4 = new Array(1, 2, 3); // 与arr1相同
const arr5 = new Array(5); // 创建长度为5的空数组
访问数组元素
使用索引访问数组元素(索引从0开始):
const fruits = ['apple', 'banana', 'orange'];
console.log(fruits[0]); // 输出: 'apple'
console.log(fruits[2]); // 输出: 'orange'
修改数组元素
通过索引直接修改数组元素:
fruits[1] = 'pear';
console.log(fruits); // 输出: ['apple', 'pear', 'orange']
常用数组方法
添加元素到数组末尾:
fruits.push('grape');
console.log(fruits); // 输出: ['apple', 'pear', 'orange', 'grape']
从数组末尾移除元素:
const lastFruit = fruits.pop();
console.log(lastFruit); // 输出: 'grape'
console.log(fruits); // 输出: ['apple', 'pear', 'orange']
从数组开头添加元素:
fruits.unshift('strawberry');
console.log(fruits); // 输出: ['strawberry', 'apple', 'pear', 'orange']
从数组开头移除元素:
const firstFruit = fruits.shift();
console.log(firstFruit); // 输出: 'strawberry'
console.log(fruits); // 输出: ['apple', 'pear', 'orange']
遍历数组
使用for循环遍历数组:
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}
使用forEach方法:
fruits.forEach(function(fruit) {
console.log(fruit);
});
使用for...of循环:

for (const fruit of fruits) {
console.log(fruit);
}
数组转换
将数组转换为字符串:
const str = fruits.join(', ');
console.log(str); // 输出: 'apple, pear, orange'
从字符串创建数组:
const str2 = 'a,b,c,d';
const arr6 = str2.split(',');
console.log(arr6); // 输出: ['a', 'b', 'c', 'd']
数组高级操作
使用map方法转换数组:
const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // 输出: [2, 4, 6]
使用filter方法过滤数组:
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // 输出: [2]
使用reduce方法累计值:
const sum = numbers.reduce((acc, num) => acc + num, 0);
console.log(sum); // 输出: 6
多维数组
创建和访问二维数组:

const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[1][2]); // 输出: 6
数组解构
从数组中提取值到变量:
const [first, second, third] = fruits;
console.log(first); // 输出: 'apple'
console.log(second); // 输出: 'pear'
扩展运算符
合并数组:
const arr7 = [1, 2, 3];
const arr8 = [4, 5, 6];
const combined = [...arr7, ...arr8];
console.log(combined); // 输出: [1, 2, 3, 4, 5, 6]
复制数组:
const arr9 = [...arr7];
console.log(arr9); // 输出: [1, 2, 3]
数组查找
使用indexOf查找元素位置:
const index = fruits.indexOf('pear');
console.log(index); // 输出: 1
使用includes检查元素是否存在:
const hasApple = fruits.includes('apple');
console.log(hasApple); // 输出: true
数组排序
排序数字数组:
const unsorted = [3, 1, 4, 2];
const sorted = unsorted.sort((a, b) => a - b);
console.log(sorted); // 输出: [1, 2, 3, 4]
排序字符串数组:
const unsortedFruits = ['banana', 'apple', 'pear'];
const sortedFruits = unsortedFruits.sort();
console.log(sortedFruits); // 输出: ['apple', 'banana', 'pear']






