Home  >  Article  >  Web Front-end  >  Introduction to JavaScript object serialization, toString() and valueOf() usage

Introduction to JavaScript object serialization, toString() and valueOf() usage

不言
不言forward
2019-03-14 11:49:082648browse

This article brings you an introduction to JavaScript object serialization, toString() and valueOf() usage. It has certain reference value. Friends in need can refer to it. Hope it helps.

Serialization

JSON.stringify() handles objects

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" }" }"

When the value of the object is undefined and Object, it will be ignored, if it is NaN and Infinity is null, the object instance For example, d, add double quotes to both key and value.

JSON.stringify() handles arrays

let arr = [undefined, Object, Symbol(""), { e: 'nice' }]
console.log(JSON.stringify(arr)) 
//输出 "[null, null, null, { "e": "nice" }]"

Custom serialization

You can override the toJSON() method. Custom serialization

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() of the object

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

When both toString and valueOf exist, when operating, they will try to convert to a basic type. First look for valueOf. If the basic type is returned, Type, this only calls valueOf. If it is not, for example, an object, go to toString. If it also returns Object, an error will be reported

The above is the detailed content of Introduction to JavaScript object serialization, toString() and valueOf() usage. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete