JS对象序列化、对象的toString()与对象的valueOf()

29次阅读

共计 1008 个字符,预计需要花费 3 分钟才能阅读完成。

序列化
JSON.stringify() 处理对象
let obj = {
val: undefined,
a: NaN,
b: Infinity,
c: new Date(),
d: {e: ‘nice’},
y: Object
}
console.log(JSON.stringify(obj))
// 输出 “{“a”: null, “b”: null, “c”: “2019-03-13T12:01:44.295Z”, “d”: “{ “e”: “nice”}” }”
当对象的 value 为 undefined 和 Object 时会被忽略,为 NaN 和 Infinity 为 null, 对象实例如 d,为 key 和 value 都加上双引号
JSON.stringify() 处理数组
let arr = [undefined, Object, Symbol(“”), {e: ‘nice’}]
console.log(JSON.stringify(arr))
// 输出 “[null, null, null, { “e”: “nice”}]”
当成员为 undefined、Object、Symbol 时为 null, 对象也是为 key 和 value 都加上双引号
自定义序列化
可以重写 toJSON() 方法进行自定义序列化
let obj = {
x: 1,
y: 2,
re: {
re1: 1,
re2: 2,
toJSON: function(){
return this.re1 + this.re2;
}
}
}
console.log(JSON.stringify(obj))
// 输出 “{“x”:1, “y”:2, “re”:3}”
对象的 toSting()
let obj = {x:1, y:2}
console.log(obj.toString()) // 输出 “[object Object]”

obj.toString = function(){
return this.x + this.y;
}
“Result” + obj; // 输出 “Result3” 调用了 toString
+obj; // 输出 “3” 调用了 toString

obj.valueOf = function(){
return this.x + this.y + 100;
}
“Result” + obj; // 输出 “Result103” 调用了 toString
当 toString 和 valueOf 都存在时,在进行操作时,都会尝试转换成基本类型,先找 valueOf, 如果返回基本类型,这只调用 valueOf,如果不是,比如是对象的话,就去找 toString, 如果也返回 Object,就会报错

正文完
 0