如何在JavaScript中使用$ {var}变量?

时间:2018-08-22 15:54:24

标签: javascript ecmascript-6 compiler-errors

我试图使用EcmaScript 6功能,使用以下功能在引号中添加变量:

'Sample Text ${variable}'

使用以下代码:

Cat.prototype.info = function(){
    console.log('Name: ${this.name}');
    console.log('Gender: '+this.gender);
    console.log('Color: '+this.color);
    console.log('Breed: '+this.breed);
    console.log('Emotion: '+this.emotion);
    console.log('Action: '+this.action);
};

但是,在控制台上注销时,我只能获得文字代码作为String。

我在犯错误吗?还是我的Web浏览器或IDE不支持该功能?

2 个答案:

答案 0 :(得分:1)

您应该使用反勾``。这称为模板字符串,${}中的变量将根据其值求值。这还将启用多行字符串。

Cat.prototype.info = function(){
    console.log(`Name: ${this.name}`);
    console.log('Gender: '+this.gender);
    console.log('Color: '+this.color);
    console.log('Breed: '+this.breed);
    console.log('Emotion: '+this.emotion);
    console.log('Action: '+this.action);
};

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

答案 1 :(得分:0)

您需要使用反引号进行字符串内插``而不是''

相关问题