Skip to content

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

@Jamlee

Description

@Jamlee

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

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    new-exampleA proposal of the new example

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions