在检查每个键、值对 Javascript 的同时遍历 Hashtable

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12628045/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 10:53:44  来源:igfitidea点击:

Iterate thru Hashtable while checking each key, value pair Javascript

javascripthashforeach

提问by Psyllex

Possible Duplicate:
How do I enumerate the properties of a javascript object?

可能的重复:
如何枚举 javascript 对象的属性?

I"m trying to iterate thru a hashtable. But I need to check the values each time I run through it.

我正在尝试遍历哈希表。但每次运行时我都需要检查这些值。

How would I use a foreach table to do this? in sudo code I'd like to do this:

我将如何使用 foreach 表来做到这一点?在 sudo 代码中,我想这样做:

var tHash = {
 name: n,
 date: d,
 labels: l,
}

foreach(value in tHash){
   if(tHash.name== somevalue){do something};
   if(tHash.label == somevalue) {do something};

That's essentially what I'd like to do but not real sure how to start it out.

这基本上就是我想做的,但不确定如何开始。

Edit: The isn't just one hash it's an array of hashes...I should've mentioned that at the beginning the way I put the code is the way I was loading the array of hashes with a for loop.

编辑:这不仅仅是一个散列,它是一个散列数组......我应该在开始时提到我放置代码的方式是我使用 for 循环加载散列数组的方式。

回答by pce

You can iterate through the Keys of a Hashobject with a for ... inLoop. You get each property (key) of the Hash and can also access the Value with the property.

您可以使用循环遍历 Hashobject 的键for ... in。您可以获得哈希的每个属性(键),还可以使用该属性访问值。

var tHash = {
  name: "n",
  date: "d",
  labels: "l" 
}

for (var key in tHash){
  console.log(key + " -> " + tHash[key]));   
  // if (key == "name") doSomething();
}

回答by Jeremy J Starcher

This works, as is.

这有效。

var tHash = {
 name: "Jeremy",
 date: "0",
 labels: 4
}

if (tHash.name === "Jeremy") {alert("Welcome, Master")};
if (tHash.labels !== 0) {alert("There is a label waiting")};