您现在的位置是:网站首页 > 数组基础文章详情

数组基础

数组的定义与创建

数组是JavaScript中最基础的数据结构之一,用于存储有序的元素集合。在JavaScript中,数组可以包含不同类型的元素,并且长度可以动态变化。

// 数组字面量创建方式
const fruits = ['apple', 'banana', 'orange'];

// 使用Array构造函数
const numbers = new Array(1, 2, 3);

// 创建空数组
const emptyArray = [];

数组的基本操作

访问数组元素

数组元素通过从0开始的索引访问:

const colors = ['red', 'green', 'blue'];
console.log(colors[0]); // 输出: 'red'
console.log(colors[2]); // 输出: 'blue'

修改数组元素

可以直接通过索引修改数组元素:

const animals = ['cat', 'dog', 'bird'];
animals[1] = 'elephant';
console.log(animals); // 输出: ['cat', 'elephant', 'bird']

获取数组长度

使用length属性获取数组元素数量:

const letters = ['a', 'b', 'c', 'd'];
console.log(letters.length); // 输出: 4

数组的常用方法

添加和删除元素

const stack = [];

// 末尾添加元素
stack.push('first');
stack.push('second');

// 末尾删除元素
stack.pop();

// 开头添加元素
stack.unshift('zero');

// 开头删除元素
stack.shift();

数组拼接

concat方法用于合并数组:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = arr1.concat(arr2);
console.log(combined); // 输出: [1, 2, 3, 4]

数组切片

slice方法返回数组的一部分:

const numbers = [0, 1, 2, 3, 4, 5];
const part = numbers.slice(1, 4);
console.log(part); // 输出: [1, 2, 3]

数组迭代方法

forEach

对数组每个元素执行函数:

const nums = [1, 2, 3];
nums.forEach(num => {
  console.log(num * 2);
});
// 输出:
// 2
// 4
// 6

map

创建新数组,包含原数组元素处理后的结果:

const prices = [10, 20, 30];
const discounted = prices.map(price => price * 0.9);
console.log(discounted); // 输出: [9, 18, 27]

filter

基于条件筛选数组元素:

const scores = [85, 92, 45, 68, 91];
const passing = scores.filter(score => score >= 70);
console.log(passing); // 输出: [85, 92, 91]

数组搜索和排序

indexOf和includes

查找元素位置或检查是否存在:

const tools = ['hammer', 'screwdriver', 'wrench'];
console.log(tools.indexOf('wrench')); // 输出: 2
console.log(tools.includes('pliers')); // 输出: false

sort

数组排序:

const randomNumbers = [3, 1, 4, 1, 5, 9];
randomNumbers.sort((a, b) => a - b);
console.log(randomNumbers); // 输出: [1, 1, 3, 4, 5, 9]

多维数组

JavaScript支持数组嵌套:

const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

console.log(matrix[1][1]); // 输出: 5

数组解构

ES6引入的解构赋值可以方便地从数组提取值:

const rgb = [255, 128, 64];
const [red, green, blue] = rgb;
console.log(red, green, blue); // 输出: 255 128 64

数组与字符串转换

join方法将数组转为字符串:

const words = ['Hello', 'world', '!'];
const sentence = words.join(' ');
console.log(sentence); // 输出: "Hello world !"

split方法将字符串转为数组:

const data = 'apple,orange,banana';
const fruits = data.split(',');
console.log(fruits); // 输出: ['apple', 'orange', 'banana']

数组的扩展运算符

ES6扩展运算符可以简化数组操作:

const arr1 = [1, 2];
const arr2 = [3, 4];
const combined = [...arr1, ...arr2];
console.log(combined); // 输出: [1, 2, 3, 4]

数组的reduce方法

reduce方法将数组缩减为单个值:

const purchases = [12.99, 5.99, 8.50];
const total = purchases.reduce((sum, price) => sum + price, 0);
console.log(total); // 输出: 27.48

数组的find和findIndex

查找满足条件的元素或索引:

const users = [
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Bob'},
  {id: 3, name: 'Charlie'}
];

const user = users.find(u => u.id === 2);
console.log(user); // 输出: {id: 2, name: 'Bob'}

数组的some和every

检查数组元素是否满足条件:

const ages = [18, 22, 25, 30];
const allAdult = ages.every(age => age >= 18);
console.log(allAdult); // 输出: true

数组的fill方法

用固定值填充数组:

const emptyArray = new Array(5);
emptyArray.fill(0);
console.log(emptyArray); // 输出: [0, 0, 0, 0, 0]

数组的flat和flatMap

处理嵌套数组:

const nested = [1, [2, 3], [4, [5]]];
const flattened = nested.flat(2);
console.log(flattened); // 输出: [1, 2, 3, 4, 5]

数组的Array.from

从类数组对象创建数组:

const str = 'hello';
const chars = Array.from(str);
console.log(chars); // 输出: ['h', 'e', 'l', 'l', 'o']

数组的Array.isArray

检查变量是否为数组:

const arr = [1, 2, 3];
console.log(Array.isArray(arr)); // 输出: true
console.log(Array.isArray({})); // 输出: false

上一篇: 对象基础

下一篇: 错误处理机制

我的名片

网名:~川~

岗位:console.log 调试员

坐标:重庆市-九龙坡区

邮箱:cc@qdcc.cn

沙漏人生

站点信息

  • 建站时间:2013/03/16
  • 本站运行
  • 文章数量
  • 总访问量
微信公众号
每次关注
都是向财富自由迈进的一步