如何在IE9上显示对象的内容

时间:2012-05-14 06:37:25

标签: javascript

var obj = {'test1':"value1", "test2": "value2" }
console.log(obj);

reuslt

[object, Object]

是否可以在IE9上显示对象不使用JSON.stringify的内容?
如下所示

{'test1':"value1", "test2": "value2" }

3 个答案:

答案 0 :(得分:6)

尝试使用console.dir()代替console.log() - 这也适用于其他浏览器的控制台。

另请参阅MSDN文章Internet Explorer 9 Developer Tools Deep Dive – Part 3: Debugging JavaScript

答案 1 :(得分:1)

如果您只是想在不使用完整比例库的情况下查看复杂对象中的内容,可以使用以下代码:

var complexObject = { 
    "first field": "first value", "second": function() {
        alert("hello");
    }, 
    "third": ["I", "am", "an", "array"]
};

var complexObjectString = "";
for (var key in complexObject) {
    complexObjectString += key + ": " + complexObject[key] + "\n";
}
alert(complexObjectString);​

Live test case

答案 2 :(得分:0)

在IE9中,您需要处于标准模式才能使用JSON对象;例如,您必须拥有doctype。

这不起作用:Live copy | source

<html>
<head>
<meta charset=utf-8 />
<title>Test Page</title>
</head>
<body>
<p>Without a doctype</p>
<script>
(function() {

  try {
    var obj = {
      foo: "bar"
    };

    var str = JSON.stringify(obj);

    display("<code>" + str + "</code>");
  }
  catch (e) {
    display("Exception: " + (e.message || e.toString()));
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }
})();
</script>
</body>
</html>

失败,错误JSON未定义。

如果你添加

<!doctype html>

到顶部,它有效:Live copy | source