如何在网页中显示数组的完整对象?

时间:2019-03-06 14:38:46

标签: javascript html

我在显示数组项时遇到了一些问题。我尝试从localStorage进行显示,但不知道如何按值排序,因此我将所有项目转换为数组然后对其进行排序。但是现在我不知道如何显示该数组。我尝试了for语句,它仅返回一个对象,这意味着它们不再为我的'x'上升计数。它显示的只是[object Object]。有人有建议吗?

function loadPlayer() {

  const lsOutput = document.getElementById("lsOutput");
  var l;
  if (localStorage.length < 5) {
    l = localStorage.length;
  } else {
    l = 5;
  }
  //Sắp xếp localstorage

  var listPlayer = [{
    playerName: '',
    score: ''
  }];
  for (var i = 0; i < l; i++) {
    const key = localStorage.key(i);
    const value = localStorage.getItem(key);
    lsOutput.innerHTML += `${i+1}- ${key}: ${value}<br/>`;
    listPlayer.push({
      playerName: key,
      score: value
    });
  }
  listPlayer.shift();
  //Sort array
  Array.prototype.sortOnValue = function(key) {
    this.sort(function(a, b) {
      if (a[key] < b[key]) {
        return -1;
      } else if (a[key] > b[key]) {
        return 1;
      }
      return 0;
    });
  }
  listPlayer.sortOnValue("score");
  console.log(listPlayer);
  //const p1Output = document.getElementById("xxxccc");
  for (var x = 0; x < listPlayer.length; x++) {
    //plOutput.innerHTML = document.writeln(listPlayer[x]);
    //plOutput.innerHTML = listPlayer.toString();
    document.getElementById("xxxccc").innerHTML = JSON.stringify(listPlayer[x].toString());
  }

}

2 个答案:

答案 0 :(得分:1)

您需要对对象使用JSON.stringify:

lsOutput.innerHTML += `${i+1}- ${key}: ${JSON.stringify(value)}<br/>`;

答案 1 :(得分:1)

删除.toString()并非必需。

将行更改为

document.getElementById("xxxccc").innerHTML = JSON.stringify(listPlayer[x]);