toString() 與 JSON.stringify()


1. toString

除自定義 toString,對象都調用 Object.prototype.toString,其返回對象內部屬性 [[Class]] =>" [obejct Obejct]", 自定義 toString 的,如 Array.prototype.toString 將數組串行化后使用“,”鏈接。

Object.prototype.toString

let obj = {a: '333'}

Object.prototype.toString.call(obj)

// "[object Object]"

 

Array.prototype.toString

let arr = [1,  2,  3]
Array.prototype.toString.call(arr)
// "1,2,3"

 

等同於

arr.join(",")

 

2. JSON.stringify()

JSON.stringify(value, replacer, space) 將一個 value(對象或者數組)轉換為一個 JSON 字符串,其首先調用對象自身的 toJSON()。

obj= {toJSON: function() {return '24';}}

JSON.stringify(obj)

// ""24""

 

JSON.stringify , replacer接收數組或者函數,規定哪些屬性可以被處理,哪些可以被過濾。返回 undefined 的屬性將被過濾。

JSON.stringify({a: 1, b: 'zzz', c: 'xxx'}, ["a", "c"])
// "{"a":1,"c":"xxx"}"

 

space 為數字時,指定每一級的縮進數量,為字符串時,用前 10 個字符串替換每一級的縮進。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM