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

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

不言
Release: 2019-03-14 11:49:54
forward
2672 people have browsed it

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" }" }"
Copy after login

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" }]"
Copy after login

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 }"
Copy after login

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
Copy after login

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!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template