本篇文章给大家带来的内容是关于JavaScript对象序列化、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" }]"
自定义序列化
可以重写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,就会报错
以上就是JavaScript对象序列化、toString()与valueOf()的用法介绍的详细内容
JavaScript对象序列化、toString()与valueOf()的用法介绍
最新推荐文章于 2023-01-20 09:33:52 发布