For...of vs For..in

For...In loops 可以遍歷一個(gè)object的 keys.

const shark = {
    species: "great white",
    color: "white",
    numberOfTeeth: Infinity
}
// Print property names of object
for (attribute in shark) {
    console.log(attribute);
}

Output :
species
color
numberOfTeeth



For...Of Loop is a new feature of ES6.
可用于遍歷一個(gè)可迭代的對象的值,比如array, string

// Initialize array of shark species
let sharks = [ "great white", "tiger", "hammerhead" ];

// Print out each type of shark
for (let shark of sharks) {
    console.log(shark);
}

Output :
great white
tiger
hammerhead


一個(gè)比較:

const str1 = "asdf"

for (const element of str1) {
  console.log(element);
}
console.log("------------");
const str2 = "asdf"

for (const element in str2) {
  console.log(element);
}

Output:
"a"
"s"
"d"
"f"


"0"
"1"
"2"
"3"


var arr = [3, 5, 7];
arr.foo = "hello";

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

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

Another distinction is that for..in operates on any object; it serves as a way to inspect properties on this object. for..of on the other hand, is mainly interested in values of iterable objects. Built-in objects like Map and Set implement Symbol.iterator property allowing access to stored values.

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

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