JavaScript 中三种 for 循环语句的使用总结(for、for...in、for...of)
本文总结 JavaScript 中三种常用循环语句:for、for...in 和 for...of。详细解析各自的适用场景与注意事项,重点对比 for...in 与 for...of 在遍历对象和数组时的差异,推荐使用 for...of 替代传统循环,并介绍 break 和 continue 关键字的使用。
前言
每一位 JavaScript 开发者都会频繁使用 for 循环,它是遍历数据不可或缺的工具。尽管目前许多文章建议尽量减少代码中 for 循环的使用,但不可否认,它在实际开发中依然具有极高的实用价值。本文将系统梳理前端 JavaScript 中三种主要的 for 循环语句。
for
这是应用最为广泛的循环语句,结构简单且实用,在大多数场景下性能表现良好。其唯一的不足在于过于普通,缺乏特色,导致部分开发者倾向于避免使用它。
const array = [4, 7, 9, 2, 6];
for (let index = 0; index < array.length; index++) {
const element = array[index];
console.log(element);
}
// 4, 7, 9, 2, 6
for...in
for...in 语句用于遍历对象中除 Symbol 类型以外的所有可枚举属性,遍历顺序不固定。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
// obj.color = red
// obj.name = temp
若仅需处理对象自身的属性而忽略原型链上的属性,应结合 getOwnPropertyNames() 方法或 hasOwnProperty() 方法来判断属性是否属于对象本身。
const temp = {name: "temp"};
function Apple() {
this.color = 'red';
}
Apple.prototype = temp;
const obj = new Apple();
for (const prop in obj) {
if (obj.hasOwnProperty(prop)) {
console.log(`obj.${ prop } = ${ obj[prop] }`);
}
}
// obj.color = red
此外,for...in 也可用于遍历数组,但需注意其潜在问题。
const arr = [1, 2, 3, 4, 5];
for (const key in arr) {
console.log(key)
}
// 0,1,2,3,4
使用 for...in 遍历数组时存在以下局限性:
- 索引 index 为字符串类型的数字(注意,非数值类型),无法直接进行数学运算。
- 遍历顺序可能与数组实际存储顺序不一致,甚至可能按随机顺序进行。
因此,通常不建议使用 for...in 来遍历数组。
for...of
for...of 语句针对可迭代对象(包括 Array、Map、Set、String、TypedArray、arguments 对象等)创建迭代循环,调用自定义迭代钩子,并为每个不同属性的值执行语句。
const array = ['a', 'b', 'c'];
for (const element of array) {
console.log(element);
}
// a
// b
// c
for...of 与 for...in 的主要区别如下:
- for...in 语句以任意顺序迭代对象的可枚举属性。
- for...of 语句遍历可迭代对象定义要迭代的数据。
Object.prototype.objCustom = function () { };
Array.prototype.arrCustom = function () { };
let iterable = [3, 5, 7];
iterable.foo = 'hello';
for (const key in iterable) {
console.log(key); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}
// 0, 1, 2, "foo", "arrCustom", "objCustom"
for (const key of iterable) {
console.log(key);
}
// 3, 5, 7
使用 for...of 遍历 Map 结构示例如下:
let nodes = new Map();
nodes.set("node1", "t1")
.set("node2", "t2")
.set("node3", "t3");
for (const [node, content] of nodes) {
console.log(node, content);
}
// node1 t1
// node2 t2
// node3 t3
可以看出,使用 for...of 遍历 Map 结构较为便捷,推荐使用。
总结
- 若对普通 for 循环感到厌倦,推荐使用 for...of 进行替代。
- 这三种循环均支持使用 break 关键字终止循环,以及使用 continue 关键字跳过本次循环。
- for...of 循环的适用范围最广。
到此这篇关于JavaScript中三种for循环语句使用总结的文章就介绍到这了,更多相关JS中for循环语句内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
