Javascript - 模板字符串不漂亮的打印对象

时间:2017-09-11 00:47:33

标签: 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);

输出

Pretty printing

模板字符串尝试

// Same description and properties
const logString = `Description: ${description}. Properties: ${properties}`;
console.log(logString);

输出

enter image description here

问题

如何使用模板字符串获得第一个输出(漂亮的打印)?

4 个答案:

答案 0 :(得分:9)

您的第一个示例实际上并未向string输出console。请注意properties如何作为单独的参数参数传递(因为它被逗号,包围而不是字符串连接运算符+)。

当您将object(或任何JavaScript值)作为离散参数传递给console时,它可以显示它的预期 - 包括作为交互式格式化显示,它在您的第一个示例中执行

在您的第二个示例中,您使用的是模板化字符串,但它(通常)与此相当:

logString = "Description: " + description.toString() + ". Properties: " + properties.toString()";

默认情况下,Object.prototype.toString()会返回[object Object]

为了获得模板化字符串中使用的对象的JSON(字面 JavaScript对象表示法)表示,请使用JSON.stringify

logString = `Description: ${ description }. Properties: ${ JSON.stringify( properties ) }.`

或者考虑为您自己的类型扩展toString

myPropertiesConstructor.prototype.toString = function() {
    return JSON.stringify( this );
};

答案 1 :(得分:1)

  

我可以使用ES6模板字符串来打印javascript对象吗?

当然,但是在将对象传递给模板文字之前,你必须将对象转换为漂亮的打印版本(我确信那里有库那样做。穷人的版本是JSON.stringify(obj, null, 2)

但是,由于console.log接受任意数量的参数,因此您应该将该对象作为第二个参数传递,以便它不会转换为字符串:

const logString = `Description: ${description}. Properties:`;
console.log(logString, properties);

答案 2 :(得分:0)

const logString = `Description: ${description}. Properties: ${JSON.stringify(properties, null, 2)}`;
console.log(logString);

答案 3 :(得分:0)

您可以尝试此your message ${JSON.stringify(object)}

相关问题