【问题标题】:How to store the values in hashmap in javascript如何在javascript中将值存储在hashmap中
【发布时间】:2020-04-29 11:53:58
【问题描述】:

我正在用 javascript 解析 xml 文件,我正在提取它的所有值

function loadXMLDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
  myFunction(this);
}
};
xmlhttp.open("GET", "/ccm/rpt/repository /workitem?fields=workitem/projectArea/*", true);
xmlhttp.send();
}

function myFunction(xml) {
var x,y,j, i, xmlDoc, txt,txt1;
xmlDoc = xml.responseXML;
txt = "";
txt1="";
x = xmlDoc.getElementsByTagName("contextId");
for (i = 0; i< x.length; i++) {
txt += x[i].childNodes[0].nodeValue;

}
y = xmlDoc.getElementsByTagName("name");
for (j = 0; i< y.length; j++) {
txt1 += y[j].childNodes[0].nodeValue;
}
}

现在我的目标是将 name 的值存储为 key 并将 contextId 存储为 value(HashMap 概念),那么是否可以实现相同的目标,如果我的问题听起来模棱两可,请告诉我 提前致谢!!

【问题讨论】:

    标签: javascript hashmap


    【解决方案1】:

    您可以向对象添加属性,就像它们是哈希图一样,看看这个例子:

    var myObj = {prop1: 12};
    var propName = "prop2";
    
    myObj[propName] = 10;
    
    console.log(myObj);
    

    哪些输出:

    {prop1: 12, prop2: 10}
    

    在您的示例中,假设 x 和 y 长度相等,然后我们可以在单个循环中添加到对象:

    var x,y,j, i, xmlDoc, myHashMap;
    
    xmlDoc = xml.responseXML;
    myHashMap = {};
    
    x = xmlDoc.getElementsByTagName("contextId");
    y = xmlDoc.getElementsByTagName("name");
    
    for (i = 0; i< x.length; i++) {
      var value = x[i].childNodes[0].nodeValue;
      var key = y[i].childNodes[0].nodeValue;
      myHashMap[key] = value;
    }
    
    console.log(myHashMap);
    

    【讨论】:

    • 但是,如果您再次看到我的代码,x 和 y 的值正在动态增加,但您的代码是静态的,如果可能的话,您可以参考我的代码举例吗?
    • 感谢您的快速更新,如果我想在控制台中查看输出,我应该怎么做 console.log()?
    • 比如添加什么值作为键,什么作为值
    • 是的,你可以添加console.log(myHashMap);循环后查看结果。或者 console.log(value);和 console.log(key);在循环内。
    猜你喜欢
    • 1970-01-01
    • 2015-01-01
    • 2012-02-14
    • 2015-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    相关资源
    最近更新 更多