如何在模板字符串文字中的变量内部编写变量?
How to write Variable inside of Variable in Template String literal?
log(`${chalk.magenta(' LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red('${LAUNCH_COMMAND}')}` );
这里是问题部分:${chalk.red('${LAUNCH_COMMAND}')}
LAUNCH_COMMAND
是 'production' 或 'development'。但是它在另一个 ${}
.
里面
只需使用模板字符串文字中嵌套变量的变量名
`${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)}` );
不要用引号将变量包含在字符串文字中。
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)}`);
log(`${chalk.magenta(' LAUNCH_COMMAND')} ${chalk.green('npm run: ')} ${chalk.red('${LAUNCH_COMMAND}')}` );
这里是问题部分:${chalk.red('${LAUNCH_COMMAND}')}
LAUNCH_COMMAND
是 'production' 或 'development'。但是它在另一个 ${}
.
只需使用模板字符串文字中嵌套变量的变量名
`${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)}` );
不要用引号将变量包含在字符串文字中。
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)}`);