簡體   English   中英

為什么我有時需要使用JSON.stringify,有時候不需要

[英]Why do I need to use sometimes JSON.stringify and sometimes not

有時在我的項目中,當我將值記錄到控制台時,我正在使用JSON.Stringify讀取數據,有時我不需要這樣做......我想知道為什么?

在這個例子中:

 this._productServices.getAll().do(data => console.log(data)).subscribe(products=> this.articles= products);

當我看到控制台時,有這樣的值:

(4) [{…}, {…}, {…}, {…}]

Acctualy有可讀的值數組。

但在這種情況下:

  filteredSubProducts: Group[];

 filterSubProductsByIdId(Id) {
    this.filteredSubProducts= this.articles.filter(item => item.parentId == Id);
    console.log("Products array" + this.filteredSubProducts);
  }

我得到的結果如下:

Products array[object Object],[object Object]

所以我需要在秒的情況下使用JSON.stringify()來獲取我的值[object Object],[object Object]可讀..我想知道為什么會這樣? 有時候我正在使用它,有時候我不是......

謝謝

您正在獲取它,因為您正在向Array filteredSubProducts添加字符串"Products array"

所以代碼實際上正在做

console.log("Products array" + this.filteredSubProducts.toString());

toString()方法導致[object Object]。

解決它的方法是不連接,但在console.log語句中使用逗號

console.log("Products array", this.filteredSubProducts)

現在,它允許您在不使用JSON.stringify()的情況下顯示它

現在,JSON.stringify()的優點在於它會在那時為您提供快照。 有時您更改數組,對象並在控制台中顯示為錯誤值對延遲評估。 stringify會導致它被評估,並在那個時刻看到它。

因為如果您嘗試使用字符串放置對象,Chrome將無法解析內容。 如果在將對象或數組寫入控制台之前需要“說”某些內容,則必須在兩個console命令中執行此操作或添加逗號

var myArray = [{content:"hola"}, {content:"hello"},{content:"hallo"}];

console.log("This does not work " + myArray);

console.log("This will work just ok");
console.log(myArray);

console.log("this works too" , myArray);

如果您在服務中將響應轉換為JSON,則必須在要使用該響應時進行字符串化。

res => res.json() //在這種情況下,您將需要使用stringify

這是因為您將一個字符串"Products array"與一個帶有.toString()的對象連接在一起 - 另一個字符串。 你在控制台看到的是字符串。 否則記錄整個對象。 嘗試

console.log("Products array", this.filteredSubProducts);

編輯:只是刪除toString()不起作用,因為"string" + ...之后的所有內容都首先轉換為字符串。

// does not work
console.log("Products array" + this.filteredSubProducts);

這種行為稱為類型強制 ,你可以在這篇SO答案中閱讀 ,在這篇文章或只是谷歌谷歌它更多信息

console.log()只能工作到第二級嵌套,例如,如果我運行console.log({}, {}, {}) ,數組中的所有對象都將顯示而不進行任何混淆,但是如果我嘗試登錄

console.log([
  {},
  {},
  {a: {
    a: {
      a: {}
    }
  }}
])

結果將類似[ {}, {}, { a: { a: [Object] } } ]

您仍然可以通過在任何體面的瀏覽器控制台中擴展它們來查看對象,但是終端沒有該設施,因此為了查看嵌套項,我們使用JSON.stringify()將對象及其子項轉換為字符串,然后可以很容易打印,但你可能已經注意到他們以這種方式松開了它們的縮進,因為你基本上是在打印一個字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM