for...in和for...of使用場景差別
- 一句話:遍歷對象的屬性時,用
for...in
。想遍歷數組中元素的值的話,用for...of
。
for...in 和 for...of的差別解析
-
for...in
是 ES5 標準,for...of
是 ES6 針對for...in的不足而補充的方法。
-
for...in
遍歷的是 '鍵名'。for...of
遍歷的是數組中元素的值。
- 當使用
for...in
遍歷數組的時候,咱們獲得的其實是數組的索引值(鍵值),同時若是數組存在別的屬性的話,也會被遍歷出來。for...in
甚至能夠遍歷到對象的原型方法和屬性
一個栗子
Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};
let iterable = [3, 5, 7];
iterable.foo = "hello";
for (let i in iterable) {
console.log(i); // 0, 1, 2, "foo", "arrCustom", "objCustom"
}
for (let i of iterable) {
console.log(i); // 3, 5, 7
參考
- 簡述js中 for in 與 for of 區別