In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
How to output JS class instances in the console to JSON format, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain in detail for you, people with this need can come to learn, I hope you can get something.
There is one class:
Class Point {constructor (x, y) {this.x = x; this.y = y;}}
If we output its instance in the console:
Console.log (new Point (10,20))
The output in the console is as follows:
Point {x: 10, y: 20}
So how do you output only the JSON format, not the class name "Point"?
Some students may use the following methods:
Console.log (JSON.stringify (new Point (10,20)
Of course, this method is possible, and the output is as follows:
{"x": 10, "y": 20}
But every time we output, we need to call JSON.stringify, which is a bit verbose.
Is there a more concise way?
The answer is yes.
In fact, if you are using the nodejs,console.log output class object, the inspect function is called to serialize and print the output object.
In node, there is a way to customize the object inspection function.
In version 6.6.0 or later, you can override the [util.inspect.custom] (depth, options) function of the class.
Const util = require ('util'); class Point {constructor (x, y) {this.x = x; this.y = y;} toString () {const that = this; return JSON.stringify (that);} [util.inspect.custom] (depth, options) {return this.toString ()}}
Documentation for version 8.x: https://nodejs.org/docs/latest-v8.x/api/util.html
In node v10.12.0 or later, Symbol is used and the [inspect] () function can be overridden.
Const inspect = Symbol.for ('nodejs.util.inspect.custom'); class Point {constructor (x, y) {this.x = x; this.y = y;} toString () {const that = this; return JSON.stringify (that);} [inspect] () {return this.toString ()}} console.log (new Point (10,20)); is it helpful for you to read the above? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.