Skip to main content

for...in(循环对象)

概述

for...in 语句以任意顺序遍历一个对象的除 Symbol 以外的可枚举属性,包括继承的可枚举属性。

var obj = { a: 1, b: 2, c: 3 };

for (var prop in obj) {
console.log("obj." + prop + " = " + obj[prop]);
}

// Output:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

区别

  • 推荐在循环对象属性的时候,使用 for...in,在遍历数组的时候的时候使用 for...of
  • for...in 循环出的是 key,for...of 循环出的是 value

以下示例显示了与 Array 一起使用时,for...of 循环和 for...in 循环之间的区别

Object.prototype.objCustom = function () {};
Array.prototype.arrCustom = function () {};

let iterable = [3, 5, 7];
iterable.foo = "hello";

for..in

for (let i in iterable) {
console.log(i); // logs 0, 1, 2, "foo", "arrCustom", "objCustom"
}

//下面的函数说明了hasOwnProperty()的用法:继承的属性不显示。
for (let i in iterable) {
if (iterable.hasOwnProperty(i)) {
console.log(i); // logs 0, 1, 2, "foo"
}
}

for..of

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

链接

优秀文章: