javascript ECMAScript模板文字(如“some ${string}”)不起作用

ukdjmx9f  于 2022-12-17  发布在  Java
关注(0)|答案(7)|浏览(81)

我想尝试使用template literals,但它不起作用:它显示的是字面变量名,而不是值。我使用的是Chrome v50.0.2(和jQuery)。

示例

console.log('categoryName: ${this.categoryName}\ncategoryElements: ${this.categoryElements} ');

输出

${this.categoryName}
categoryElements: ${this.categoryElements}
14ifxucb

14ifxucb1#

JavaScript * 模板文本 * 需要反引号,而不是直引号。

您需要使用反引号(也称为“重音符号”-您可以在1键if you're using a QWERTY keyboard旁边找到它)而不是单引号来创建模板文本。
反勾在许多编程语言中很常见,但对JavaScript开发人员来说可能是新事物。
示例:

categoryName="name";
categoryElements="element";
console.log(`categoryName: ${this.categoryName}\ncategoryElements: ${categoryElements} `)

输出:

VM626:1 categoryName: name 
categoryElements: element

参见:
Usage of the backtick character (`) in JavaScript

rqenqsqc

rqenqsqc2#

这里有三个引号,但只有一个入口有效,我们可以将其用作模板文字:

  1. " "(键盘上的键)不起作用:
console.log("Server is running on port: ${PORT}")
  1. ' '(键盘上的Shift + 2键)不起作用:
console.log('Server is running on port: ${PORT}')
  1. (键盘上的Alt + Num96键)工作正常:
console.log(`Server is running on port: ${PORT}`)

bq8i3lrv

bq8i3lrv3#

它只适用于如果你使用backticks,在我的Mac pro是```,这是上面的tab键。
如果你使用单引号或双引号,它不会工作!

niknxzdl

niknxzdl4#

// Example
var person = {
  name: "Meera",
  hello: function(things) {
    console.log(`${this.name} Says hello ${things}`);
  }
}

// Calling function hello
person.hello("World");

//Meera Says hello World
j13ufse2

j13ufse25#

我无法获得所需的输出。我使用的是单引号',这是不正确的,它打印的是相同的消息。
键盘上的反勾号低于~。使用shift + ~可获得反勾号
希望有帮助。

kgsdhlau

kgsdhlau6#

模板文字不使用双引号/单引号,而使用反勾号

const test = 'Test'
console.log(`test: ${test}`)

有关更多https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals,请转到Mdn文档

v2g6jxz6

v2g6jxz67#

1.)将.jshitrc添加到与app.js和其他文件相同的文件夹级别
2.)将其放入新创建的文件{“esversion”:6)
3.)从不使用单引号'使用反引号'

相关问题