JavaScript 中的 for...in 與 for...of

英文 |?https://dev.to/mehmehmehlol/for-in-vs-for-of-in-javascript-174g
翻譯 | web前端開發(fā)(ID:web_qdkf)
相當(dāng)長一段時(shí)間,我一直在努力充分理解for...in和for...of之間的差異。如果你是通過 Google 或 dev.to feed 發(fā)現(xiàn)我的這篇文章,我可以有把握地假設(shè)你可能想知道同樣的事情。
for...in 和 for...of 是我們都熟悉的 for 循環(huán)的替代方案。但是,for...in 和 for...of 用于不同的場合,其主要取決于你要查找的內(nèi)容,而我們知道的 for 循環(huán)基本上可以在任何情況下使用。
我們將首先討論示例/用法,然后我們將分解它們中的每一個(gè)。
示例/用法
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
現(xiàn)在你看到了它們是如何使用的,讓我們一一分解它們!
我們親愛的最好的朋友,for 語句
當(dāng)我們需要迭代任何東西時(shí),可以隨時(shí)使用這個(gè)基本的 for 循環(huán)。
基本語法
for ([initialization]; [condition]; [final-expression]) {statement}
迭代通常發(fā)生在block(又名{})內(nèi)部。我們將在要執(zhí)行的循環(huán)的塊中放置多個(gè)語句。你可以根據(jù)條件使用break、continue等來繼續(xù)或中斷 for 循環(huán)。
示例與?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.
快速說明:括號(hào)內(nèi)的所有表達(dá)式都是可選的。
示例與?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循環(huán)遍歷對(duì)象的所有可枚舉屬性。
如果你不知道 enumerable 是什么,我會(huì)盡力解釋它是什么?;旧夏憧梢哉J(rèn)為可枚舉屬性是key對(duì)象中的鍵值。
它也會(huì)出現(xiàn)在Object.keys()方法中。因此,如果我們查看上一節(jié)中的示例...
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鍵值對(duì)中的鍵?,這是我們的可枚舉屬性。如果你對(duì)如何檢索對(duì)象的值有基本的了解,我們將鍵視為數(shù)組中的索引并將其放在方括號(hào) ->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 或 {} 中(因?yàn)閿?shù)組也是一個(gè)對(duì)象),不建議/好的做法for...in用于迭代數(shù)組,其中索引順序很重要。
是的,數(shù)組索引也是可枚舉的屬性,但是是整數(shù)。如果我們用for...in來迭代一個(gè)數(shù)組,它的行為非常不可預(yù)測。不能保證元素按特定順序迭代。
此外,如果你想通過分配給超出數(shù)組當(dāng)前大小的索引來擴(kuò)展數(shù)組,它可能無法反映正確的索引。因此,for...of, forEach, 或for帶有數(shù)字索引的循環(huán)是迭代數(shù)組的更好方法。
for...of
現(xiàn)在是我們的第二個(gè)主角for...of。如果你不知道,for...of在 ES6 中引入。for...of已經(jīng)成為很多 JavaScript 開發(fā)者的有用迭代方法。for...of可以迭代任何可迭代對(duì)象。你把它命名為, String, Array, Object...
String
Array(從示例部分復(fù)制)const name = "Megan";for (const alphabet of name) {console.log(alphabet);}// Expected Output:// M// e// g// a// n
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.
注意側(cè)邊欄
Object.entries()返回給定對(duì)象自己的可枚舉字符串鍵屬性的數(shù)組。
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' ]// ]
那我們該如何使用它們?
本文內(nèi)容的目的是將這兩個(gè)for語句“并排”進(jìn)行學(xué)習(xí)比較,以便我們更加清楚的區(qū)分與了解它們。在這里分享一個(gè)最直接簡單的區(qū)分方法:1、for...in在迭代對(duì)象的可枚舉字符串鍵屬性對(duì)時(shí)使用。你知道{ blah1: blah blah, blah2: blah blah blah }。但不是數(shù)組!!請(qǐng)記住,無論記錄什么,都類似于記錄數(shù)組的索引,但記錄字符串,因此如果要記錄/返回值,請(qǐng)確保使用obj[key]。2、for...of在迭代可迭代對(duì)象時(shí)使用 :如果String,Array,等。下次當(dāng)你在做一些需要迭代的事情時(shí),或者只是做你的常規(guī) Leetcode 練習(xí),甚至在你的技術(shù)面試中,用for...of和for...in炫耀你新獲得的知識(shí)。最后,感謝你的閱讀,編程快樂!
學(xué)習(xí)更多技能
請(qǐng)點(diǎn)擊下方公眾號(hào)
![]()

