我可以使用 ES6 模板字符串来漂亮地打印 javascript 对象吗?这是来自 React Native 项目,其中console.log()
输出到 Chrome 调试工具。
我想要的是
const description = 'App opened';
const properties = { key1: 'val1', blah: 123 };
console.log('Description: ', description, '. Properties: ', properties);
outputs
模板字符串尝试
// Same description and properties
const logString = `Description: ${description}. Properties: ${properties}`;
console.log(logString);
outputs
Question
如何使用模板字符串获得第一个输出(带有漂亮的打印)?
你的第一个例子实际上并没有输出string
to the console
。注意如何properties
作为单独的参数参数传递(因为它被逗号包围,
而不是字符串连接运算符+
).
当你通过一个object
(或任何 JavaScript 值)console
作为一个离散的参数,它可以按照自己的意愿显示 - 包括作为交互式格式化显示,它在第一个示例中就是这样做的。
在第二个示例中,您使用的是模板化字符串,但它(通常)相当于:
logString = "Description: " + description.toString() + ". Properties: " + properties.toString()";
And Object.prototype.toString()
回报"[object Object]"
默认情况下。请注意,这是一个string
值不是特别有用。
为了获得 JSON (字面上地 JavaScript Object N旋转)模板字符串使用中使用的对象的表示JSON.stringify
:
logString = `Description: ${ description }. Properties: ${ JSON.stringify( properties ) }.`
或者考虑延长toString
对于您自己的类型:
myPropertiesConstructor.prototype.toString = function() {
return JSON.stringify( this );
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)