【问题标题】:How to loop through this Array and output to html?如何遍历这个数组并输出到 html?
【发布时间】:2019-09-23 16:48:16
【问题描述】:

我有一个简单的数组,我很难对其进行排序。我在想可能是因为时间格式,所以我不确定如何引用它或如何以这种数组格式对时间进行排序,以便稍后对其进行排序。

//为输入值创建的函数 函数放置(键,值,obj){ 对象 [键] = 值; 返回对象 }

//loads the document from ajax call
function loadDoc() {
//ajax call
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
    var data = xhttp.responseText;
//input data from webpage into dom element
    document.getElementById('next').innerHTML = data
    var test = document.getElementsByClassName('gridRow')
//create dict
    var new_dict = {}
    for(a=0;a<test.length;a++){
        if(test[a].children[2].innerText == 'Ready') {
            test[a].style.display = 'none';
            //drops into the dictionary
            put(String(test[a].children[0].innerText).replace(/\n/ig, ''), 
test[a].children[3].innerText, new_dict)
            }
    }
document.getElementById('next').innerHTML = ''  

//looping through the dict
for(var index in new_dict) {
  document.getElementById('next').innerHTML += ("<br>" + index + " : " + 
new_dict[index] + "<br>");
}

输出与名称出现的顺序相同。

【问题讨论】:

  • 我很难排序”你想在哪里排序?
  • 您的 for 循环似乎也没有完全显示在这里 - new_dict 数组在哪里声明?
  • 请分享创建数组的代码

标签: javascript html arrays loops


【解决方案1】:

任何创建new_dict 的东西都创建不正确。它是一个数组,但创建它的代码使用它就像一个普通对象。我会修复它,例如,它是一个对象数组。

但是以您当前的结构:

如果您想按属性名称的字母顺序循环遍历其属性,您可以使用Object.keys 获取键并对其进行排序,然后通过map 循环遍历结果创建输出:

document.getElementById('next').innerHTML = Object.keys(new_dict)
    .sort((a, b) => a.localeCompare(b))     // Sorts lexicographically (loosely, "alphabetically")
    .map(key => escapeHTML(key + ": " + new_dict[key]))
    .join("<br>");                          // Joins them with <br> in-between
}

...其中escapeHTML 编码&amp;&lt;,因为您正在生成HTML。一个快速而肮脏的版本(对于上述情况来说已经足够好了)是这样的:

// ONLY good enough to handle text that isn't in attributes
function escapeHTML(str) {
    return str.replace(/&/g, "&amp;").replace(/</g, "&lt;");
}

【讨论】:

  • 这在修改我的 Dict 以包含前导 0 后起作用,例如 @user1211530 建议
【解决方案2】:

根据您的数组似乎被填充的方式,并寻求最简单的解决方案:您为什么不将时间值标准化,以便适当地预先添加 0?

" john doe": "00:19:57" “人造人”:“00:36:40” “查尔斯·辛”:“01:35:37”

【讨论】:

  • 听起来很简单,让我试试吧。
【解决方案3】:

这是一个字典,而不是一个数组。将名称称为“键”而不是“索引”会更准确。特别是,您在此处拥有的字典将名称映射到时间。无论如何,您可以做的一件事是制作一个新字典,将时间映射到名称列表(因为多个名称可能具有相同的时间)。然后对该字典的键进行排序。

【讨论】:

  • 我同意,这是一本字典,但是当我控制台登录到 chrome 时,这就是 chrome 所说的。
【解决方案4】:

使用以下修复时间格式:

function put(key, value, obj) {
    obj[key] = value.replace(/(\b\d\b)/g,'0$1');
    return obj;
}

然后使用:

Object.keys(new_dict)
    .sort((a, b) => a.localeCompare(b))
    .forEach(p=>document.getElementById('next').innerHTML +="<br>" + p + " : " + 
new_dict[p] + "<br>");

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多