Johannes Schacht
Johannes Schacht

Reputation: 1334

Type of array index string or number?

when I loop over the indexes of an array they show up as string. But indexing an array using strings is forbidden. Isn't that incoherent? Why is it so?

for (const i in ["a", "b", "c"]) {
  console.log(typeof i + " " i + " " + arr[i]);  // -> string 0 'a', etc.
}
arr['0'] // ERROR ts7105: Element implicitly has an 'any' type because index expression is not of type 'number':

Upvotes: 3

Views: 1728

Answers (1)

Josef
Josef

Reputation: 3497

for ... in iterates over the keys of the given object.

An array will have its indices as keys, see Object.keys([4,5,1]) which prints ["0", "1", "2"]. To iterate a typed array use for ... of See the docs. If you need the index use a regular for(let i=0;i<arr.length;i++) or for(let [i,el] of arr.entries()) loop.

As for your question, yes it does seem incoherent, but it looks like indexing inside a loop using the loop variable allows string indices. But be aware that index + 1 will be "01" because the index is a string.

Upvotes: 4

Related Questions