js for in 與 for of 區(qū)別

JavaScript 原有的for...in循環(huán),只能獲得對(duì)象的鍵名,不能直接獲取鍵值。ES6 提供for...of循環(huán),允許遍歷獲得鍵值。

var arr = ['a', 'b', 'c', 'd'];

for (let a in arr) {
  console.log(a); // 0 1 2 3
}

for (let a of arr) {
  console.log(a); // a b c d
}

for...of循環(huán)調(diào)用遍歷器接口,數(shù)組的遍歷器接口只返回具有數(shù)字索引的屬性

let arr = [3, 5, 7];
arr.foo = 'hello';

for (let i in arr) {
  console.log(i); // "0", "1", "2", "foo"
}

for (let i of arr) {
  console.log(i); //  "3", "5", "7"
}

對(duì)于普通的對(duì)象,for...of結(jié)構(gòu)不能直接使用,會(huì)報(bào)錯(cuò),必須部署了 Iterator 接口后才能使用。但是,這樣情況下,for...in循環(huán)依然可以用來(lái)遍歷鍵名。

for...of循環(huán)可以使用的范圍包括數(shù)組、Set 和 Map 結(jié)構(gòu)、某些類(lèi)似數(shù)組的對(duì)象(比如arguments對(duì)象、DOM NodeList 對(duì)象)、后文的 Generator 對(duì)象,以及字符串。

總結(jié)

一、最原始的寫(xiě)法for循環(huán)。

for (var index = 0; index < myArray.length; index++) {
  console.log(myArray[index]);
}

這種寫(xiě)法比較麻煩,因此數(shù)組提供內(nèi)置的forEach方法。

二、forEach方法。

myArray.forEach(function (value) {
  console.log(value);
});

這種寫(xiě)法的問(wèn)題在于,無(wú)法中途跳出forEach循環(huán),break命令或return命令都不能奏效。

三、for...in循環(huán)。

for...in循環(huán)可以遍歷數(shù)組的鍵名。

for (var index in myArray) {
  console.log(myArray[index]);
}

for...in循環(huán)有幾個(gè)缺點(diǎn)。

  • 數(shù)組的鍵名是數(shù)字,但是for...in循環(huán)是以字符串作為鍵名“0”、“1”、“2”等等。
  • for...in循環(huán)不僅遍歷數(shù)字鍵名,還會(huì)遍歷手動(dòng)添加的其他鍵,甚至包括原型鏈上的鍵。
  • 某些情況下,for...in循環(huán)會(huì)以任意順序遍歷鍵名。

總之,for...in循環(huán)主要是為遍歷對(duì)象而設(shè)計(jì)的,不適用于遍歷數(shù)組。

四、for...of循環(huán)。

for...of循環(huán)相比上面幾種做法,有一些顯著的優(yōu)點(diǎn)。

for (let value of myArray) {
  console.log(value);
}
  • 有著同for...in一樣的簡(jiǎn)潔語(yǔ)法,但是沒(méi)有for...in那些缺點(diǎn)。
  • 不同于forEach方法,它可以與break、continue和return配合使用。
  • 提供了遍歷所有數(shù)據(jù)結(jié)構(gòu)的統(tǒng)一操作接口。

下面是一個(gè)使用 break 語(yǔ)句,跳出for...of循環(huán)的例子。

for (var n of fibonacci) {
  if (n > 1000)
    break;
  console.log(n);
}

上面的例子,會(huì)輸出斐波納契數(shù)列小于等于 1000 的項(xiàng)。如果當(dāng)前項(xiàng)大于 1000,就會(huì)使用break語(yǔ)句跳出for...of循環(huán)。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容