Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

Loop through a 'Hashmap' in JavaScript

I'm using this method to make artificial 'hashmaps' in javascript. All I am aiming for is key|value pairs, the actual run time is not important. The method below works fine.

Are there any other ways to loop through this?

for (var i in a_hashMap[i]) {
    console.log('Key is: ' + i + '. Value is: ' + a_hashMap[i]);
} 

I run into a problem where this outputs a bunch of undefined keys after the first key, when the array only contains one entry. I have a feeling it is because the code is within a loop which uses i, even though when I follow in debug it shouldn't be happening. I also cannot change i as the for loop seems to not understand the replaced var at all.

Anyone any ideas?

question from:https://stackoverflow.com/questions/6748781/loop-through-a-hashmap-in-javascript

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

1 Answer

0 votes
by (71.8m points)
for (var i in a_hashmap[i])

is not correct. It should be

for (var i in a_hashmap)

which means "loop over the properties of a_hashmap, assigning each property name in turn to i"


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...