Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

solring
solring

Posted on

     

[JS newbie] Array indexes in for...in loops.

TL;DR. The indexes got in this way may not be what you anticipated.

If your are usingfor(idx in arr) to enumerate through an Array, note that the type ofidx is actuallystring, notnumber.

>for(iinarr){console.log(`type of key${i}:${typeof(i)}`)}typeofkey0:stringtypeofkey1:stringtypeofkey2:stringtypeofkey3:stringtypeofkey4:string
Enter fullscreen modeExit fullscreen mode

That is, if you want to derive some values from the index in your loop like this:

for(iinarr){letval=i+1+arr2[i-1];// will probably become sth like "0122" rather than a number.}
Enter fullscreen modeExit fullscreen mode

Your code will either explode or behave unexpectedly.

This is because the indexes of an Array are actually enumerable properties of an Object and are of typestring. TheMDN doc has some explanation, and you can also check the indexes of an Array as properties byObject.getOwnPropertyNames.

>Object.getOwnPropertyNames(arr)['0','1','2','3','4','length']
Enter fullscreen modeExit fullscreen mode

Also, it is suggested that you'd better not use this to iterate through an Array if the order of execution is important since it is arbitrary according toMDN doc.

That's today's joke. Sorry if there is any misunderstanding and corrections are appreciated!.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

The internet is broken so I'm out here today.
  • Education
    MSc in National Taiwan University
  • Work
    Former embedded system engineer.
  • Joined

More fromsolring

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp