3

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':
4
  • 5
    array's index is number? always has been Commented Apr 27, 2021 at 12:41
  • 1
    developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 27, 2021 at 12:52
  • Forbidden is an extreme word. I mean an array is an object so you can always do things like this. It does however mean that when you iterate an array as an object all its indices are coerced into strings (which I agree is not intuitive) Commented Apr 27, 2021 at 13:28
  • It seems I couldn't make myself clear. My wondering is: Outside the for-in loop I am forced to use a number as index, e.g. arr[0]. But inside the loop, the index is a string. Commented Apr 27, 2021 at 14:56

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.