關於JSON.stringify的細節

JSON 的常規用途是同 web 服務器進行數據交換。
在向 web 服務器發送數據時,數據必須是字符串。
通過 JSON.stringify() 把 JavaScript 對象轉換爲字符串。

js會有一個自動拆箱功能,而stringify正好相反

let a1 ="1";
let a2 =1
let b1 ="true"
let b2 =true
let c ="str"

//默認會自動拆箱(布爾值不會)
console.log(a1+":"+b1+":"+c)//1:true:str
console.log(a2+":"+b2+":"+c)//1:true:str
console.log(a1==a2)//true
console.log(b1==b2)//false

// 布爾值、數字、字符串的包裝對象在序列化過程中會自動轉換成對應的原始值。
console.log(JSON.stringify(a1)+":"+JSON.stringify(b1)+":"+JSON.stringify(c))// "1":"true":"str"
console.log(JSON.stringify(a2)+":"+JSON.stringify(b2)+":"+JSON.stringify(c))//  1: true: "str"

console.log(JSON.stringify(a1)==JSON.stringify(a2))//false
console.log(JSON.stringify(b1)==JSON.stringify(b2))//false
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章