Node.js – util.inspect() 方法
util.inspect() 方法返回对象的字符串表示形式,这些对象旨在用于调试过程。
语法
util.inspect(object, [showHidden], [depth], [colors])
参数
参数定义如下
- object − 给定为输入的 JavaScript 基本类型或对象。
- 选项
- showHidden − 默认情况下设置为 false。如果为 true,则此选项包括格式化结果中包含的不可枚举符号和属性。WeakMap 和 WeakSet 也包括在内。
- depth − 它指定在格式化对象时要应用的递归次数。
- colors − 如果此值设置为 true,则输出将使用 ANSI 颜色代码设置样式。传递的颜色是可自定义的。
- customInspect − 如果此值设置为 false,则不会调用函数。
- showProxy − 如果此值设置为 true,则代理检查包括目标和处理程序对象。默认值为“false”。
- maxArrayLength − 此值指定数组的最大数量。
- maxStringLength − 这指定在格式化时要包含的最大字符数。将这些值设置为 null 或 infinity 以显示所有元素。
- breakLength − 这是跨多行拆分的输入值。
- compact − 此输入将在文本中超过 breakLength 的换行符处换行。
- sorted − 如果设置为 true,则映射和集合以及对象中的所有条目都将排序。
- getters − 如果这些值设置为 true,则会检查 getter。
示例
创建一个文件“inspect.js”并复制以下代码片段。创建文件后,使用命令“node inspect.js”运行此代码。
// Node util.inspect Demo Example
// Importing the util library
const util = require('util');
// Creating nested Objects
const nestedObject = {};
nestedObject.a = [nestedObject];
nestedObject.b = [['a', ['b']], 'b', 'c', 'd'];
nestedObject.b = {};
nestedObject.b.inner = nestedObject.b;
nestedObject.b.obj = nestedObject;
// Inspect by basic method
console.log("1. ", util.inspect(nestedObject));
// Random class
class tutorialsPoint { }
// Inspecting the tutorialsPoint class object
console.log("2. ", util.inspect(new tutorialsPoint()));
// Inspect by passing options to method
console.log("3. ", util.inspect(
nestedObject, true, 0, false));
// Inspect by calling option name
console.log("4. ", util.inspect(nestedObject,
showHidden = false, depth = 0, colorize = true));
// Directly passing the JSON data
console.log("5. ", util.inspect([
{ name: "Raj", city: "Delhi" },
{ name: "Arun", city: "Mumbai" },
{ name: "Diva", city: "Chandigarh" }],
false, 3, true));输出
C:\home
ode>> node inspect.js 1. <ref *1> { a: [ [Circular *1] ], b: <ref *2> { inner: [Circular *2], obj: [Circular *1] } } 2. tutorialsPoint {} 3. { a: [Array], b: [Object] } 4. { a: [Array], b: [Object] } 5. [ { name: 'Raj', city: 'Delhi' }, { name: 'Arun', city: 'Mumbai' }, { name: 'Diva', city: 'Chandigarh' } ]
您可以根据您的用例使用不同的选项来获取不同的检查对象。
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP