如何在Template String literal中的Variable中写入变量?

时间:2017-07-14 18:45:11

标签: javascript node.js object-literal template-strings

log(`${chalk.magenta(' LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red('${LAUNCH_COMMAND}')}` );

以下是问题部分:${chalk.red('${LAUNCH_COMMAND}')}

LAUNCH_COMMAND是“生产”或“发展”。但是它在另一个${}内。

enter image description here

2 个答案:

答案 0 :(得分:3)

Demo

只需在模板字符串文字

中使用嵌套变量的变量名称
`${chalk.red(LAUNCH_COMMAND)}` // for nested sting literal just use the variable name 
const LAUNCH_COMMAND = 'hi';
console.log(`${chalk.magenta('  LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red(LAUNCH_COMMAND)}` );

enter image description here

答案 1 :(得分:-1)

您不要在带有引号的字符串文字中包装变量。

log(`${chalk.magenta(  LAUNCH_COMMAND)} ${chalk.green(npm run: )} ${chalk.red(LAUNCH_COMMAND})` ); 

^虽然我不清楚为什么你要编写这样的字符串背后的背景,但假设是有效的。我假设它是某种动态输出。



var b = "Cats"
var c = "Dogs"

function concat(one, two) {

  return `${one} and ${two}`;

}

function compare(one, two) {

  var ans = one == two ? 'Are the same' : 'Are not the same';
  return ans;

}

console.log(`${concat(b, c)} - ${compare(b, c)}`);