簡體   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