JavaScript 中的 for...in 与 for...of

英文 | https://dev.to/mehmehmehlol/for-in-vs-for-of-in-javascript-174g

翻译 | web前端开发(ID:web_qdkf)

相当长一段时间,我一直在努力充分理解for...in和for...of之间的差异。如果你是通过 Google 或 dev.to feed 发现我的这篇文章,我可以有把握地假设你可能想知道同样的事情。

for...in 和 for...of 是我们都熟悉的 for 循环的替代方案。但是,for...in 和 for...of 用于不同的场合,其主要取决于你要查找的内容,而我们知道的 for 循环基本上可以在任何情况下使用。

我们将首先讨论示例/用法,然后我们将分解它们中的每一个。

示例/用法

for

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


function printArr(arr) {
  for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
  }
}


console.log(printArr(arr));


// 1
// 2
// 3
// 4
// 5

for...in

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


function printObj(obj) {
  for (let prop in obj) {
    console.log(`prop: ${prop}`)
    console.log(`obj[prop]: ${obj[prop]}`)
  }
}


console.log(printObj(obj));


// prop: a
// obj[prop]: 1
// prop: b
// obj[prop]: 2
// prop: c
// obj[prop]: 3

for...of

const arrOf = [1, 2, 3, 4, 5]


function printArrOf(arr) {
  for (let ele of arr) {
    console.log(ele);
  }
}


console.log(printArrOf(arrOf));


// 1
// 2
// 3
// 4
// 5

现在你看到了它们是如何使用的,让我们一一分解它们!

我们亲爱的最好的朋友,for 语句

当我们需要迭代任何东西时,可以随时使用这个基本的 for 循环。

基本语法

for ([initialization]; [condition]; [final-expression]) {
  statement
}

迭代通常发生在block(又名{})内部。我们将在要执行的循环的块中放置多个语句。你可以根据条件使用break、continue等来继续或中断 for 循环。

示例与 break

for (let i = 0;; i++) {
  console.log(i);
  if (i > 5) break;
}


// Expected Output: 
// 0
// 1
// 2
// 3
// 4
// 5
// 6


// Explanation: The loop breaks when i is larger than 5.

快速说明:括号内的所有表达式都是可选的。

示例与 continue

for (let i = 0; i < 10; i++) {
  if (i === 7) continue;
  else console.log(i);
}


// Expected Output:
// 0
// 1
// 2
// 3
// 4
// 5
// 6
// 8
// 9


// Explanation: if i is equal to 7, we will skip that i and move on to the next index.

for...in

for...in循环遍历对象的所有可枚举属性。

如果你不知道 enumerable 是什么,我会尽力解释它是什么。基本上你可以认为可枚举属性是key对象中的键值。

它也会出现在Object.keys()方法中。因此,如果我们查看上一节中的示例...

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


function printObj(obj) {
  for (let prop in obj) {
    console.log(`prop: ${prop}`)
    console.log(`obj[prop]: ${obj[prop]}`)
  }
}


console.log(printObj(obj));


// prop: a
// obj[prop]: 1
// prop: b
// obj[prop]: 2
// prop: c
// obj[prop]: 3

prop是key键值对中的键 ,这是我们的可枚举属性。如果你对如何检索对象的值有基本的了解,我们将键视为数组中的索引并将其放在方括号 ->obj[prop]中,如下所示。

const obj = { 
  name: "Megan", 
  age: "do the Math", 
  role: "front-end developer" 
}


for (const property in obj) {
  console.log(property);
}


// Expected Output:
// name
// age
// role

到目前为止,我们的示例都在 object 或 {} 中(因为数组也是一个对象),不建议/好的做法for...in用于迭代数组,其中索引顺序很重要。

是的,数组索引也是可枚举的属性,但是是整数。如果我们用for...in来迭代一个数组,它的行为非常不可预测。不能保证元素按特定顺序迭代。

此外,如果你想通过分配给超出数组当前大小的索引来扩展数组,它可能无法反映正确的索引。因此,for...of, forEach, 或for带有数字索引的循环是迭代数组的更好方法。

for...of

现在是我们的第二个主角for...of。如果你不知道,for...of在 ES6 中引入。for...of已经成为很多 JavaScript 开发者的有用迭代方法。for...of可以迭代任何可迭代对象。你把它命名为, String, Array, Object...

String

const name = "Megan";


for (const alphabet of name) {
  console.log(alphabet);
}


// Expected Output:
// M
// e
// g
// a
// n

Array(从示例部分复制)

const arrOf = [1, 2, 3, 4, 5]


function printArrOf(arr) {
  for (let ele of arr) {
    console.log(ele);
  }
}


// Expected Output:
// 1
// 2
// 3
// 4
// 5

Object(借助Object.entries())

const obj = {
  name: "Megan", 
  age: "do the Math", 
  role: "front-end developer" 
};


for (const [key, value] of Object.entries(obj)) {
  console.log(key, value);
  console.log(`${key}: ${value}`);
}


// Expected Output:
// name Megan
// name: Megan
// age do the Math
// age: do the Math
// role front-end developer
// role: front-end developer


// Explanation: the [key, value] is a destructure of the result from Object.entries.

注意侧边栏
Object.entries()返回给定对象自己的可枚举字符串键属性的数组。

const obj = {
  name: "Megan", 
  age: "do the Math", 
  role: "front-end developer" 
};


Object.entries(obj)
// [
//  [ 'name', 'Megan' ],
//  [ 'age', 'do the Math' ],
//  [ 'role', 'front-end developer' ]
// ]

那我们该如何使用它们?

本文内容的目的是将这两个for语句“并排”进行学习比较,以便我们更加清楚的区分与了解它们。

在这里分享一个最直接简单的区分方法:
1、for...in在迭代对象的可枚举字符串键属性对时使用。你知道{ blah1: blah blah, blah2: blah blah blah }。

但不是数组!!请记住,无论记录什么,都类似于记录数组的索引,但记录字符串,因此如果要记录/返回值,请确保使用obj[key]。

2、for...of在迭代可迭代对象时使用 :如果String,Array,等。

下次当你在做一些需要迭代的事情时,或者只是做你的常规 Leetcode 练习,甚至在你的技术面试中,用for...of和for...in炫耀你新获得的知识。

最后,感谢你的阅读,编程快乐!

学习更多技能

请点击下方公众号

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值