JS对象序列化、对象的toString()与对象的valueOf()
文章目录
序列化
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()和valueOf()
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,就会报错
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论