for in 是ES5標准,遍歷key。(可遍歷對象、數組、字符串的key)
for of 是ES6標准,遍歷value。(可遍歷對象、數組、字符串的value)
//字符串 let s = "helloabc"; for(let c of s) { console.log(c); } 結果: h e l l o a b c
總結: for in總是得到對像的key或數組,字符串的下標
for of 總是得到對像的value或數組,字符串的值,還可以遍歷Map和Set
var set = new Set(); set.add("a").add("b").add("d").add("c"); var map = new Map(); map.set("a",1).set("b",2).set(999,3); for (let v of set) { console.log(v); } console.log("--------------------"); for(let [k,v] of map) { console.log(k,v); }