为什么 for...in 循环中的变量是一个字符串?

Why is the variable in a for...in loop a string?

我使用 for...in 循环来记录值,我注意到 for...in 循环中的变量(i,在本例中)是一个字符串。

for (var i in ['a', 'b', 'c']) {
  console.log(i, typeof i)
}

我在 ECMAScript specifications 标题为“for-in、for-of 和 for-await-of 声明”的部分中搜索了有关此的任何信息,但无法找到在这上面找到任何东西。

我的问题是,规范中有关于此的任何内容吗?如果没有,为什么它是一个字符串?

for..in calls EnumerateObjectProperties,这样做:

Return an Iterator object (26.1.1.2) whose next method iterates over all the String-valued keys of enumerable properties of O. The iterator object is never directly accessible to ECMAScript code. The mechanics and order of enumerating the properties is not specified but must conform to the rules specified below.

所有对象属性都是字符串或符号。甚至可以设置和检索数组的属性 就好像 它们是数字一样被解释为字符串(并在通过 for..in 或其他 属性 枚举检索时作为字符串检索Object.keysObject.getOwnPropertyNames 等方法)。您还可以看到 [[OwnPropertyKeys]](),它表示:

The Type of each element of the returned List is either String or Symbol.

例如 Array.prototype.push, you can see:

5. For each element E of items, do:
  a. Perform ? Set(O, ! ToString(len), E, true).

属性 赋值总是导致设置 属性 ,它可以是字符串或符号。 (参见 isPropertyKey - 如果类型(参数)是字符串,return 真。如果类型(参数)是符号,return 真。否则 Return 假.