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 个字符串替换每一级的缩进。

猜你喜欢

转载自www.cnblogs.com/xiabaoying/p/12107381.html