#337·wtfjs

`for..in` iterating array indices: `string`, Not just `number`

Author: JamleeCreated Feb 6, 2025Updated Feb 6, 2025
Labelsnew-example

When iterating over the indices of an array, the index values are "string" rather than just "number".

javascript
let a = [1, 2, 3]; 
for (let i in a) {
     console.log(typeof i); //  string
}

Arrays are essentially objects:

  1. In JavaScript, arrays are a special type of object. The indices of an array are actually the property names of the object, except that these property names are strings in numeric form. For example, the array [1, 2, 3] can be regarded as an object {0: 1, 1: 2, 2: 3}. How the for...in loop works.
  2. The for...in loop iterates over all enumerable properties of an object. For an array, these properties are the indices of the array. And the property names of an object (including the indices of an array) are always of the string type in JavaScript.