JavaScript forEach、for-in和for-of的区别总结

1. forEach

forEach用来遍历数组,用forEach有以下特征:

  • 相比于for循环,形式更加简洁
  • 没有返回值
  • 不能使用breakcontinue来控制循环
  • 若使用return,则会跳过当前循环,直接进入下一个循环,不会跳出外层函数

forEach中,使用breakcontinue,会直接报错:

const arr = [0, 1, 2, 3, 4, 5];

arr.forEach((item, index) => {
    if (index === 2) break; // SyntaxError: Illegal break statement
    console.log(item);
});
const arr = [0, 1, 2, 3, 4, 5];

arr.forEach((item, index) => {
    if (index === 2) continue; // SyntaxError: Illegal continue statement
    console.log(item);
});

如下代码,在index===2的时候,希望跳出test函数,然而实际上只是跳过了当前的循环:

const arr = [0, 1, 2, 3, 4, 5];

function test() {
    arr.forEach((item, index) => {
        if (index === 2) return;
        console.log(item);
    });
}

test();
// 0
// 1
// 3
// 4
// 5

而同样功能,使用for循环就可以直接跳出test函数:

const arr = [0, 1, 2, 3, 4, 5];

function test() {
    const len = arr.length;
    for (let i = 0; i < len; i++) {
        if (i === 2) return;
        console.log(arr[i]);
    }
}

test();
// 0
// 1

2. for-in

for...in语句以任意顺序遍历一个对象的除Symbol以外的可枚举属性。

for (variable in object){
	...
}
  • variable:在每次迭代时,variable会被赋值为不同的key,即属性名
  • object:非Symbol类型的可枚举属性被迭代的对象。

for ... in更适合遍历对象,不建议与数组一起使用,因为遍历顺序有可能不是按照实际数组的索引顺序。

for ... in会遍历所有的可枚举属性,包括原型

const obj = { a: 1, b: 2, c: 3 };

function myObj() {
    this.name = 'Jack';
}

myObj.prototype = obj;

const user = new myObj();

for (const prop in user) {
    console.log(`user.${prop} = ${user[prop]}`);
}
// user.name = Jack
// user.a = 1
// user.b = 2
// user.c = 3

如果想仅迭代自身的属性,需要使用hasOwnProperty()方法判断某个属性是否是该对象的实例属性:

const obj = { a: 1, b: 2, c: 3 };

function myObj() {
    this.name = 'Jack';
}

myObj.prototype = obj;

const user = new myObj();

for (const prop in user) {
    if (user.hasOwnProperty(prop)) {
        console.log(`user.${prop} = ${user[prop]}`);
    }
}
// user.name = Jack

3. for-of

for...of语句在可迭代对象(包括 ArrayMapSetStringTypedArrayarguments对象等 )上创建一个迭代循环,并为每个不同属性的值执行语句。

for (variable of iterable) {
	...
}
  • variable:在每次迭代中,将不同属性的分配给variable
  • iterable:被迭代枚举其属性的对象。

forEach()不同的是,它可以正确响应breakcontinuereturn语句。

迭代数组

const arr = [10, 20, 30];

for (const value of arr) {
    console.log(value);
}
// 10
// 20
// 30

迭代Map

const map = new Map([
    ['a', 1],
    ['b', 2],
    ['c', 3],
]);

for (const entry of map) {
    console.log(entry);
}
// ["a", 1]
// ["b", 2]
// ["c", 3]

for (const [key, value] of map) {
    console.log(value);
}
// 1
// 2
// 3

迭代arguments对象:

(function () {
    for (const argument of arguments) {
        console.log(argument);
    }
})(1, 2, 3);

// 1
// 2
// 3

4. 总结

  • forEach是数组的方法,遍历数组,没有返回值,不能使用breakcontinue,不能用return到跳出外层函数。
  • for...in语句以任意顺序迭代对象的,包括原型。不建议与数组一起使用。
  • for...of 语句遍历可迭代对象
  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

火星飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值