如何在控制台等html元素中显示对象?

时间:2016-02-21 14:04:13

标签: javascript object console.log

我想在一个名为" demo"的段落中显示整个对象,我想要显示的对象与它在控制台中的方式类似。但它不是返回" [对象对象]"在段落内。 有没有办法在段落中显示它像console.log方法? 这是我的代码:



var obj = {
  subobj: {prop1: "value1", prop2: "value2", prop3: "value3"},
};

var var1 = "subobj";

function func() {
  for (x in obj) {
    if (var1 == x) {
      // i want it to be shown like the console.log method
      // console.log(obj[x])
      document.getElementById("demo").innerHTML = obj[x];
    }
  }
};

func()




3 个答案:

答案 0 :(得分:2)

尝试并使用此:

document.getElementById("demo").innerHTML = JSON.stringify(obj[x])

答案 1 :(得分:2)

您只需stringify整个对象,而不是循环遍历每个键/值对,并将结果放在pre元素中:

function func(obj) {

  // null refers to an optional replacer function which we won't
  // use in this instance. 2 is an optional parameter to set the 
  // indentation, in this case 2 spaces
  var json = JSON.stringify(obj, null, 2);
  document.getElementById("demo").innerHTML = json;
};

输出

{
  "subobj": {
    "prop1": "value1",
    "prop2": "value2",
    "prop3": "value3"
  }
}

DEMO

答案 2 :(得分:1)

也许这会有所帮助:

var obj = {"objects":[
    {"prop1": "obj1 value1", "prop2": "obj1 value2"},
    {"prop1": "obj 2 value1", "prop2": "obj2 value2"}
]};

function func() {
    var html = "";
    for (var i=0; i < obj.objects.length; i++) {
            // i want it to be shown like the console.log method
            // console.log(obj[x])
        html += "<p>" + obj.objects[i].prop1 + obj.objects[i].prop2  + "</p>";

        }

    document.getElementById("demo").innerHTML = html;
    }
func();

您使用了&#34; obj [x]&#34;,但您的对象中没有对象数组。 而且这更好,因为你将html缓存在一个字符串中,只有当你调用&#34; document.getElementById(&#34; demo&#34;)。innerHTML = html;&#34;

祝你好运!