在 JavaScript 中循环遍历“Hashmap”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6748781/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Loop through a 'Hashmap' in JavaScript
提问by myol
I'm using thismethod 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.
我正在使用这种方法在 javascript 中制作人工“哈希图”。我的目标是键|值对,实际运行时间并不重要。下面的方法工作正常。
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.
我遇到了一个问题,当数组只包含一个条目时,这会在第一个键之后输出一堆未定义的键。我有一种感觉,这是因为代码在一个使用 i 的循环中,即使当我在调试时它不应该发生。我也无法更改 i 因为 for 循环似乎根本不理解被替换的 var。
Anyone any ideas?
有人有什么想法吗?
回答by jhurshman
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
"
这意味着“遍历 的属性a_hashmap
,依次将每个属性名称分配给i
”
回答by Raynos
for (var i = 0, keys = Object.keys(a_hashmap), ii = keys.length; i < ii; i++) {
console.log('key : ' + keys[i] + ' val : ' + a_hashmap[keys[i]]);
}
回答by dchhetri
You can use JQuery function
您可以使用 JQuery 函数
$.each( hashMap, function(index,value){
console.log("Index = " + index + " value = " + value);
})
回答by spraff
Do you mean
你的意思是
for (var i in a_hashmap) { // Or `let` if you're a language pedant :-)
...
}
i
is undefined when the for-loop gets set up.
i
设置 for 循环时未定义。
回答by Atmaram
Try this in order to print console correctly...
试试这个以正确打印控制台...
for(var i in a_hashMap) {
if (a_hashMap.hasOwnProperty(i)) {
console.log('Key is: ' + i + '. Value is: ' + a_hashMap[i]);
}
}
回答by Binita Bharati
Iterating through a map in vanilla Javacsript is simple .
在 vanilla Javacsript 中遍历地图很简单。
var map = {...};//your map defined here
for(var index in map)
{
var mapKey = index;//This is the map's key.
for(i = 0 ; i < map[mapKey].length ; i++)
{
var mapKeyVal = map[mapKey];//This is the value part for the map's key.
}
}
回答by Ketu
This is an old post, but one way I can think of is
这是一个旧帖子,但我能想到的一种方法是
const someMap = { a: 1, b: 2, c: 3 };
Object.keys(someMap)
.map(key => 'key is ' + key + ' value is ' + someMap[key]);
Should this way of iterating be used? Are there any issues with this approach?
是否应该使用这种迭代方式?这种方法有什么问题吗?