在 JavaScript 中循环遍历“Hashmap" [英] Loop through a 'Hashmap' in JavaScript

查看:30
本文介绍了在 JavaScript 中循环遍历“Hashmap"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 this 方法在 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.

还有其他方法可以循环吗?

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

我遇到了一个问题,当数组只包含一个条目时,它会在第一个键之后输出一堆未定义的键.我有一种感觉,这是因为代码在一个使用 i 的循环中,即使我在调试时它不应该发生.我也无法更改 i 因为 for 循环似乎根本不理解替换的 var.

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.

有人有什么想法吗?

推荐答案

for (var i in a_hashmap[i])

不正确.应该是

for (var i in a_hashmap)

意思是遍历a_hashmap的属性,将每个属性名依次赋值给i"

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

这篇关于在 JavaScript 中循环遍历“Hashmap"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆