ale*_*ger 6 javascript string ecmascript-6
我可以使用ES6模板字符串来打印javascript对象吗?这来自React Native项目,console.log()输出到Chrome调试工具.
const description = 'App opened';
const properties = { key1: 'val1', blah: 123 };
console.log('Description: ', description, '. Properties: ', properties);
Run Code Online (Sandbox Code Playgroud)
输出
// Same description and properties
const logString = `Description: ${description}. Properties: ${properties}`;
console.log(logString);
Run Code Online (Sandbox Code Playgroud)
输出
如何使用模板字符串获得第一个输出(使用漂亮的打印)?
Dai*_*Dai 11
你的第一个例子实际上没有输出string到console.请注意如何properties作为单独的参数参数传递(因为它被逗号,而不是字符串连接运算符包围+).
当您将object(或任何JavaScript值)传递console给离散参数时,它可以显示它的方式 - 包括作为交互式格式化显示,它在您的第一个示例中执行.
在你的第二个例子中,你正在使用模板化字符串,但它(通常)与此相当:
logString = "Description: " + description.toString() + ". Properties: " + properties.toString()";
Run Code Online (Sandbox Code Playgroud)
并默认Object.prototype.toString()返回[object Object].
为了获得模板化字符串中使用的对象的JSON(字面上的 JavaScript对象表示法)表示,请使用JSON.stringify:
logString = `Description: ${ description }. Properties: ${ JSON.stringify( properties ) }.`
Run Code Online (Sandbox Code Playgroud)
或者考虑扩展toString您自己的类型:
myPropertiesConstructor.prototype.toString = function() {
return JSON.stringify( this );
};
Run Code Online (Sandbox Code Playgroud)