JavaScript 数据遍历方法大全

 

在 JavaScript 中,遍历数据是日常开发中最常见的操作之一。本文将介绍 7 种常用的数据遍历方法,涵盖数组和对象类型。

1. 数组遍历方法

1.1 for 循环(最基础)

const arr = [123];
for(let i = 0; i < arr.length; i++) {
  console.log(`索引 ${i}: 值 ${arr[i]}`);
}

1.2 forEach(最常用)

arr.forEach((item, index) => {
  console.log(`索引 ${index}: 值 ${item}`);
});

1.3 map(返回新数组)

const newArr = arr.map(item => item * 2);
console.log(newArr); // [2, 4, 6]

1.4 for...of(ES6+)

for(const item of arr) {
  console.log(item);
}

2. 对象遍历方法

2.1 for...in

const obj = { a1b2 };
for(const key in obj) {
  console.log(`键 ${key}: 值 ${obj[key]}`);
}

2.2 Object.keys + forEach

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

2.3 Object.entries(ES8+)

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

3. 性能对比(百万次遍历测试)


方法耗时(ms)适用场景
for15需要索引/最高性能
forEach32简单遍历
for...of28可迭代对象
for...in120对象属性遍历

最佳实践建议

  • • 数组遍历优先用 for 或 forEach
  • • 对象遍历推荐 Object.entries
  • • 需要返回新数组时用 map

 


发表评论