文章

数组与对象

数组与对象

Node.js 数组与对象完全指南

本文将详细介绍 Node.js 中数组和对象的使用方法,包括创建、操作和常用技巧。

数组 (Array)

创建数组

1
2
3
4
5
6
7
8
9
10
11
// 字面量方式
const fruits = ['apple', 'banana', 'orange'];

// 构造函数方式
const numbers = new Array(1, 2, 3, 4, 5);

// 使用 Array.from()
const fromString = Array.from('hello'); // ['h', 'e', 'l', 'l', 'o']

// 使用 Array.of()
const ofArray = Array.of(1, 2, 3); // [1, 2, 3]

常用数组方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const numbers = [1, 2, 3, 4, 5];

// 添加/删除元素
numbers.push(6); // 末尾添加
numbers.pop();   // 末尾删除
numbers.unshift(0); // 开头添加
numbers.shift();    // 开头删除

// 切片和拼接
const sliced = numbers.slice(1, 3); // [2, 3] - 不改变原数组
const spliced = numbers.splice(1, 2, 'a', 'b'); // 从索引1开始删除2个元素,并添加新元素

// 查找
const found = numbers.find(item => item > 3); // 4
const index = numbers.findIndex(item => item === 3); // 2

// 迭代
numbers.forEach(item => console.log(item));
const doubled = numbers.map(item => item * 2);
const filtered = numbers.filter(item => item % 2 === 0);

// 其他实用方法
const hasEven = numbers.some(item => item % 2 === 0);
const allEven = numbers.every(item => item % 2 === 0);
const sum = numbers.reduce((acc, curr) => acc + curr, 0);

多维数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 创建二维数组
const matrix = [
  [1, 2, 3],
  [4, 5, 6],
  [7, 8, 9]
];

// 访问元素
console.log(matrix[1][2]); // 6

// 遍历二维数组
matrix.forEach(row => {
  row.forEach(cell => {
    console.log(cell);
  });
});

对象 (Object)

创建对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// 字面量方式
const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

// 构造函数方式
const car = new Object();
car.make = 'Toyota';
car.model = 'Camry';
car.year = 2020;

// 使用 Object.create()
const animal = Object.create(null);
animal.type = 'dog';
animal.breed = 'Labrador';

对象操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
const user = {
  name: 'Alice',
  age: 25,
  email: 'alice@example.com'
};

// 访问属性
console.log(user.name); // 点表示法
console.log(user['age']); // 括号表示法

// 添加/修改属性
user.occupation = 'Developer';
user['age'] = 26;

// 删除属性
delete user.email;

// 检查属性是否存在
console.log('name' in user); // true
console.log(user.hasOwnProperty('age')); // true

// 获取所有键、值或键值对
const keys = Object.keys(user);
const values = Object.values(user);
const entries = Object.entries(user);

对象方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const product = {
  name: 'Laptop',
  price: 999,
  inStock: true,
  
  // 方法
  getDescription() {
    return `${this.name} - $${this.price}`;
  },
  
  updatePrice(newPrice) {
    this.price = newPrice;
    return this.price;
  }
};

console.log(product.getDescription()); // Laptop - $999
product.updatePrice(899);

对象迭代

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const student = {
  name: 'Bob',
  grade: 'A',
  subjects: ['Math', 'Science', 'History']
};

// for...in 循环
for (const key in student) {
  console.log(`${key}: ${student[key]}`);
}

// Object.entries 结合 forEach
Object.entries(student).forEach(([key, value]) => {
  console.log(`${key}: ${value}`);
});

// Object.keys 结合 forEach
Object.keys(student).forEach(key => {
  console.log(`${key}: ${student[key]}`);
});

数组与对象的结合

对象数组

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
const users = [
  { id: 1, name: 'John', age: 30 },
  { id: 2, name: 'Jane', age: 25 },
  { id: 3, name: 'Bob', age: 35 }
];

// 查找特定用户
const user = users.find(user => user.id === 2);

// 过滤用户
const youngUsers = users.filter(user => user.age < 30);

// 提取特定属性
const names = users.map(user => user.name);

// 排序
const sortedByAge = users.sort((a, b) => a.age - b.age);

// 计算平均值
const averageAge = users.reduce((sum, user) => sum + user.age, 0) / users.length;

数组作为对象属性

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
const library = {
  name: 'City Library',
  books: [
    { title: 'JavaScript Basics', author: 'John Doe', available: true },
    { title: 'Node.js Guide', author: 'Jane Smith', available: false },
    { title: 'Advanced React', author: 'Bob Johnson', available: true }
  ],
  
  // 方法
  findAvailableBooks() {
    return this.books.filter(book => book.available);
  },
  
  addBook(book) {
    this.books.push(book);
  },
  
  removeBook(title) {
    this.books = this.books.filter(book => book.title !== title);
  }
};

// 使用库方法
library.addBook({ 
  title: 'TypeScript in Practice', 
  author: 'Alice Brown', 
  available: true 
});

const availableBooks = library.findAvailableBooks();

实用技巧

解构赋值

1
2
3
4
5
6
7
8
9
10
11
12
// 数组解构
const colors = ['red', 'green', 'blue'];
const [firstColor, secondColor] = colors;

// 对象解构
const person = { name: 'John', age: 30, city: 'NY' };
const { name, age } = person;

// 函数参数解构
function printUser({ name, age }) {
  console.log(`${name} is ${age} years old`);
}

扩展运算符

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// 数组扩展
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];

// 对象扩展
const obj1 = { a: 1, b: 2 };
const obj2 = { c: 3, d: 4 };
const merged = { ...obj1, ...obj2 };

// 函数参数
function sum(...numbers) {
  return numbers.reduce((acc, curr) => acc + curr, 0);
}

深拷贝与浅拷贝

1
2
3
4
5
6
7
8
// 浅拷贝
const original = { a: 1, b: { c: 2 } };
const shallowCopy = { ...original };

// 深拷贝
const deepCopy = JSON.parse(JSON.stringify(original));

// 注意:JSON方法会忽略函数和undefined值

总结

Node.js 中的数组和对象是构建应用程序的基础。掌握它们的特性和方法对于高效开发至关重要。本文涵盖了从基础操作到高级技巧的内容,希望能帮助您更好地理解和使用这些数据结构。

记住,实践是学习的关键,尝试在自己的项目中应用这些概念,以加深理解。

本文由作者按照 CC BY 4.0 进行授权