我对此感到困惑了一段时间。让我们以这个简单的对象为例:
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" ]
}
节点在哪里存储其显示属性? (要使用的引号,显示对象的间距和换行符,等等)
答案 0 :(得分:0)
您可以使用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));