在 JavaScript
中,遍历数据是日常开发中最常见的操作之一。本文将介绍 7 种常用的数据遍历方法,涵盖数组和对象类型。
1. 数组遍历方法
1.1 for 循环(最基础)
const arr = [1, 2, 3];
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 = { a: 1, b: 2 };
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) | 适用场景 |
for | 15 | 需要索引/最高性能 |
forEach | 32 | 简单遍历 |
for...of | 28 | 可迭代对象 |
for...in | 120 | 对象属性遍历 |
最佳实践建议:
- • 数组遍历优先用
for
或forEach
- • 对象遍历推荐
Object.entries
- • 需要返回新数组时用
map
没有评论:
发表评论