javascript - 通过节点显示 javascript 对象的格式
问题描述
我对此感到困惑有一段时间了。让我们来看看这个简单的对象:
let animalList = {
animals : ["dog","cat","horse"],
colors : ["blue","red"]
};
console.log(animalList);
它给了我这个输出:
{ animals: [ 'dog', 'cat', 'horse' ],
colors: [ 'blue', 'red' ] }
假设我想要这个输出,而不是(我知道它纯粹是装饰性的):
{
animals: [ "dog", "cat", "horse" ],
colors: [ "blue", "red" ]
}
节点在哪里存储它的显示属性?(要使用的引号、显示对象的间距和换行符等)
解决方案
您可以使用JSON.stringify
( mdn ) 进行一些格式设置:
let animalList = {
animals : ["dog","cat","horse"],
colors : ["blue","red"]
};
console.log(JSON.stringify(animalList, null, 2));
但是要自定义处理新行的方式,您必须创建自己的 obj->string 函数,例如:
let prettyPrint = (obj, indent = 0, indentStep = 2) => {
if (Array.isArray(obj))
return `[ ${obj.map(a => prettyPrint(a, indent + 1, indentStep)).join(', ')}]`;
if (typeof obj === 'string')
return `"${obj}"`;
if (typeof obj === 'number')
return number;
if (typeof obj === 'undefined')
return 'undefined';
if (typeof obj === 'object') {
let spaces = ' '.repeat((indent + 1) * indentStep);
let inside = Object.entries(obj).map(([key, value]) =>
`${spaces}${key}: ${prettyPrint(value, indent + 1, indentStep)}`);
return `{\n${inside.join(',\n')}\n},`;
}
};
let animalList = {
animals: ["dog", "cat", "horse"],
colors: ["blue", "red"]
};
console.log(prettyPrint(animalList));
推荐阅读
- uwp - 将文件解压缩到 UWP C++/WinRT 中的目录
- php - 如何将双循环查询转换为 PDO?
- java - 与 Maven 的 Internet 连接被阻止
- javascript - 值更改时输入标签触发事件的Rails实现
- php - 如何根据复选框输入向用户个人资料插入信息?
- python - plotly_express scatter 的功能有问题
- c - 为什么我的 exe 文件在 cmd 中可以正常工作,但在双击时不能正常工作?
- bash - AWS 数据管道,从 bash shell 脚本运行卸载 redshift 并保存到 S3
- macros - 在运行时调用宏扩展
- java - FragmentHome.this 中的问题如何解决