NodeJS-常量/变量评估不起作用

时间:2019-10-18 15:10:18

标签: node.js

Accordingly to NodeJS documentation

console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!, to stderr

但是,如果您考虑在REPL(在线或本地)中运行以下简单代码,则此方法在任何地方都行不通:

const x = '10';
console.log("x value is ${x}"); // Always prints ${x}, but never the evaluated value

我可能在这里缺少什么吗?

谢谢

2 个答案:

答案 0 :(得分:1)

您不需要将其作为字符串控制台记录,您需要使用模板文字。

const x = '10';
console.log(`x value is ${x}`);


console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something bad happened], to stderr

const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);

模板文字文档-https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

答案 1 :(得分:1)

除了@NicolaeMaties的回答外,我还忽略了前三个句子中的内容。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals#Description

这是反勾号的重音符号,而不是单引号。但是我仍然相信NodeJS文档也许可以再说一次明显的(!)。