繁体   English   中英

Javascript console.log产生[object Object]结果

[英]Javascript console.log yields [object Object] result

我有一个Ajax调用,它返回一个JSON编码的数组。 当我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是[object Object]”,是因为JavaScript将字符串串联+将对象转换为单个串联的字符串,然后再将其附加到该字符串。 它将对象转换为对象类型的字符串,但是如您所知,它不显示对象的内容。 没有JSON.stringify(),Console.log不能用于以这种方式呈现字符串+对象。

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

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”属性。 更少的输入=酷豆! 请享用 :)

你试过了吗

console.log(JSON.stringify(msg))

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

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

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM