Javascript 控制台.log产生 [object Object] 结果

Javascript console.log yields [object Object] result

本文关键字:Object 结果 object 控制台 log 产生 Javascript      更新时间:2023-09-26

我有一个返回 JSON 编码数组的 Ajax 调用。当我console.log()收到的数据时,我得到的正是我所期望的 - 数组的字符串表示形式。但是,当我JSON.parse()这个字符串然后尝试console.log()结果时,我得到一系列[object Object]。为什么?

法典:

<script type="text/javascript">
function shout(msg) {
  console.log(msg);
}
//Ajax call returns string JsonData
shout("jsonData is "+jsonData); //Produces the string-representation of my array
var parsedData=JSON.parse(jsonData);
shout("parsedData is "+parsedData); //Produces a series of [object Object]

我做错了什么?

您看到此消息"parsedData is [object Object]"的原因是 JavaScript 在将字符串附加到该字符串之前将字符串 + 强制转换为单个串联字符串。它将对象强制转换为对象类型的字符串,但如您所知,它不显示对象的内容。Console.log 不能用于以这种方式呈现字符串 + 对象,没有 JSON.stringify()。

要使代码正常工作,请尝试以下操作:

shout("parsedData is " + JSON.stringify(parsedData));

以下是它的工作原理:

<script>
  function shout(msg) {
    console.log(msg);
  }
  //Ajax call returns string JsonData
  var jsonData = '{"a":"abc","b":"cool beans","c":"xyz"}';
  shout("jsonData is " + jsonData); //Produces the string-representation of my array
  var parsedData = JSON.parse(jsonData);
  shout("parsedData is " + parsedData); //Produces a series of [object Object]
  shout("JSON.stringify(parsedData) is " + JSON.stringify(parsedData));
  // The JSON.stringify function, essentially does this:
  var output = '{';
  for (var key in parsedData) {
    output += '"' + key + '":"' + parsedData[key] + '",';
  }
  output += '}';
  output = output.replace(',}','}');
  shout("output is " + output);
</script>

输出如下所示:

jsonData is {"a":"abc","b":"cool beans","c":"xyz"}
parsedData is [object Object]
JSON.stringify(parsedData) is {"a":"abc","b":"cool beans","c":"xyz"}
output is {"a":"abc","b":"cool beans","c":"xyz"}

顺便说一句,我们不再需要在脚本标签中使用 type="text/javascript" 属性。少打字=酷豆!享受:)

它现在是一个对象,因此您可以像访问任何对象一样访问属性。我不知道你的对象中应该有什么,但你明白了。

for (var i = 0; i < parsedData.length; i++) {
    shout(parsedData[i].property1);
    shout(parsedData[i].property2);
    ...
}

你试过吗

console.log(JSON.stringify(msg))

如果这不起作用,请提供部分服务器端代码,以便我们提供帮助。

当您将对象附加到字符串时,它会在对象上调用toString。例如:

console.log('hey ' + { a: 1 }); // 'hey [object Object]'

如果要有一个字符串后跟一个实际对象,可以将该对象作为另一个参数传递给console.log

console.log('hey', { a: 1 }); // 'hey' Object {a: 1}