为什么这个 JS for-in 循环只记录了一个 属性 的键,而不是整个 属性?

Why does this JS for-in loop log just the key of a property, and not the entire property?

MDN 说:

The for..in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

如果我输入这个 JavaScript 代码:

var myObject = {0:'cat', 1:'dog', 2:'fish'};

for (var x in myObject) {
    console.log(x);
}

我得到这个输出:

0
1
2

如果它正在迭代 "over the enumerable properties",为什么它不像这样记录整个 属性?

0: 'cat'
1: 'dog'
2: 'fish'

我知道我也可以通过 myArray['x'] 让它记录值,但我想知道为什么它只按原样记录键。

这是否只是 for-in 循环的内置逻辑的一部分,并且与它们的预期用途有关?

这是 javascript for in 循环的预期行为。如果你想要 属性 的值,那么你应该这样做:

var myObject = {0:'cat', 1:'dog', 2:'fish'};

for (var x in myObject) {
    console.log(myObject[x]);
}

在您的示例对象中,您具有三个属性。这些属性的名称是 0、1 和 2。这些属性的值是 "cat"、"dog" 和 "fish"。 For in 循环枚举属性的名称而不是值。