本篇文章给大家带来的内容是关于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 调用了tostringobj.valueof = function(){ return this.x + this.y + 100; }result + obj; //输出 result103 调用了tostring
当tostring和valueof都存在时,在进行操作时,都会尝试转换成基本类型,先找valueof,如果返回基本类型,这只调用valueof,如果不是,比如是对象的话,就去找tostring,如果也返回object,就会报错
以上就是javascript对象序列化、tostring()与valueof()的用法介绍的详细内容。