Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
252 views
in Technique[技术] by (71.8m points)

javascript - Strings as keys of array

When using strings as keys of an array, console is showing that the array without these declared values and while iterating by this values where keys are string aren't displayed? , although i can get value of them.

>> var arr = [ 0, 1, 2, 3 ];
   undefined

>> arr["something"] = "aught";
   "aught"

>> arr
   [0, 1, 2, 3]

>> arr["something"]
   "aught"

>> for( var i = arr.length; i--; console.log( arr[ i ] ) );
   3
   2
   1
   0

I understand that arrays are objects which has implemented some kind of 'enumerate' interface in JavaScript's engine.

Most interesting is that interpreter isn't throwing either warning or error, so I spent some time of searching for where data could be lost.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In javascript there are 2 type of arrays: standard arrays and associative arrays

  • [ ] - standard array - 0 based integer indexes only
  • { } - associative array - javascript objects where keys can be any strings

So when you define:

var arr = [ 0, 1, 2, 3 ];

you are defining a standard array where indexes can only be integers. When you do arr["something"] since something (which is what you use as index) is not an integer you are basically defining a property to the arr object (everything is object in javascript). But you are not adding an element to the standard array.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...