JavaScript 中三种 for 循环语句的使用总结(for、for...in、for...of)

作者:小括号时间:2026-10-24 12:49:01浏览:565

本文总结 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 遍历数组时存在以下局限性:

  1. 索引 index 为字符串类型的数字(注意,非数值类型),无法直接进行数学运算。
  2. 遍历顺序可能与数组实际存储顺序不一致,甚至可能按随机顺序进行。

因此,通常不建议使用 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 结构较为便捷,推荐使用。

总结

  1. 若对普通 for 循环感到厌倦,推荐使用 for...of 进行替代。
  2. 这三种循环均支持使用 break 关键字终止循环,以及使用 continue 关键字跳过本次循环。
  3. for...of 循环的适用范围最广。

到此这篇关于JavaScript中三种for循环语句使用总结的文章就介绍到这了,更多相关JS中for循环语句内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!

作者最新文章