JS中的遍历

一.基础使用

1. 遍历数组

for 循环
const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
   
  console.log(numbers[i]);
}

// 输出:
// 1
// 2
// 3
// 4
// 5
forEach
const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number, index) => {
   
  console.log(`Index: ${
     index}, Number: ${
     number}`);
});

// 输出:
// Index: 0, Number: 1
// Index: 1, Number: 2
// Index: 2, Number: 3
// Index: 3, Number: 4
// Index: 4, Number: 5
map
const numbers = [1, 2, 3, 4, 5];

const doubled = numbers.map(number => number * 2);
console.log(doubled);

// 输出: [2, 4, 6, 8, 10]
filter
const numbers = [1, 2, 3, 4, 5];

const evenNumbers = numbers.filter(number => number % 2 === 0);
console.log(evenNumbers);

// 输出: [2, 4]
reduce
const numbers = [1, 2, 3, 4, 5];

const sum = numbers.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
console.log(sum);

// 输出: 15

2. 遍历对象

for…in
const person = {
    name: 'Alice', age: 30, city: 'New York' };

for (const key in person) {
   
  if (person.hasOwnProperty(key)) {
   
    console.log(`${
     key}: ${
     person[key]}`);
  }
}

// 输出:
// name: Alice
// age: 30
// city: New York
Object.keys
const person = {
    name: 'Alice', age: 30, city: 'New York' };

Object.keys(person).forEach(key => {
   
  console.log(`${
     key}: ${
     person[key]}`);
});

// 输出:
// name: Alice
// age: 30
// city: New York
Object.entries
const person = {
    name: 'Alice', age: 30, city: 'New York' };

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

// 输出:
// name: Alice
// age: 30
// city: New York

3. 遍历其他可迭代对象

for…of
const numbers = [1, 2, 3, 4, 5];

for (const number of numbers) {
   
  console.log(number);
}

// 输出:
// 1
// 2
// 3
// 4
// 5

4. 遍历 Set 和 Map

Set
const set = new Set([1, 2, 3, 4, 5]);

for (const value of set) {
   
  console.log(value);
}

// 输出:
// 1
// 2
// 3
// 4
// 5
Map
const map = new Map([
  ['name', 'Alice'],
  ['age', 30],
  ['city', 'New York']
]);

for (const [key, value] of map) {
   
  console.log(`${
     key}: ${
     value}`);
}

// 输出:
// name: Alice
// age: 30
// city: New York

总结

  • 数组遍历:使用 for 循环、forEachmapfilterreduce 方法。
  • 对象遍历:使用 for...in 循环、Object.keysObject.entries 方法。
  • 其他可迭代对象遍历:使用 for...of 循环。

这些示例展示了如何在实际应用中遍历不同的数据结构,并给出了具体的输出结果。希望这些示例对您有所帮助!如果您有任何其他问题或需要更详细的解释,请随时提问。

栗子🌰

当然,我会提供一些更复杂的示例,这些示例更加贴近实际项目中的应用场景。我们将处理一些更复杂的业务逻辑,比如处理用户权限、处理数据库查询结果、处理API响应等。

1. 用户权限处理

假设我们有一个用户列表和一个角色列表,我们需要根据用户的权限来过滤用户列表。

const users = [
  {
    id: 1, name: 'Alice', role: 'admin' },
  {
    id: 2, name: 'Bob', 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值