遍历数组和对象的方法都有哪些?

在前端开发中,遍历数组和对象的方法有很多种。以下是一些常见的方法:

遍历数组

  1. for 循环
const arr = [1, 2, 3, 4, 5];
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}
  1. forEach 方法
const arr = [1, 2, 3, 4, 5];
arr.forEach((item, index) => {
  console.log(item, index);
});
  1. for...of 循环
const arr = [1, 2, 3, 4, 5];
for (const item of arr) {
  console.log(item);
}
  1. map 方法(通常用于生成新数组,但也可用于遍历)
const arr = [1, 2, 3, 4, 5];
arr.map((item, index) => {
  console.log(item, index);
  return item * 2; // 可以生成新数组,但此处主要关注遍历功能
});
  1. forIn(不推荐用于数组,因为它是为对象设计的,不会按照预期顺序遍历数组元素)

遍历对象

  1. for...in 循环
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
  if (obj.hasOwnProperty(key)) { // 确保是对象自身的属性,而不是原型链上的属性
    console.log(key, obj[key]);
  }
}
  1. Object.keys() 与 forEach/for...of 结合
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj).forEach((key) => {
  console.log(key, obj[key]);
});

// 或者使用 for...of
for (const key of Object.keys(obj)) {
  console.log(key, obj[key]);
}
  1. Object.entries() 与 forEach/for...of 结合(直接获取键值对)
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
  console.log(key, value);
});

// 或者使用 for...of
for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
}
  1. Object.values() 与 forEach/for...of 结合(只获取值)
const obj = { a: 1, b: 2, c: 3 };
Object.values(obj).forEach((value) => {
  console.log(value);
});

// 或者使用 for...of
for (const value of Object.values(obj)) {
  console.log(value);
}
posted @   王铁柱6  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示