代码之家  ›  专栏  ›  技术社区  ›  Ron I

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

  •  81
  • Ron I  · 技术社区  · 9 年前

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

    实例

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

    输出

    ${this.categoryName}
    categoryElements: ${this.categoryElements}
    
    8 回复  |  直到 3 年前
        1
  •  0
  •   Akshay    2 年前

    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

        2
  •  0
  •   Edwald    2 年前

    有三个引号,但只有一个入口可用作模板文字:

    1. " " ( 键盘上的键)不工作:
    console.log("Server is running on port: ${PORT}")
    
    1. ' ' ( 转移 + 2. 键盘上的键)不工作:
    console.log('Server is running on port: ${PORT}')
    
    1. ` ` ( 中高音 + 数字96 键盘上的键)正在工作:
    console.log(`Server is running on port: ${PORT}`)
    

    Screenshot of console.log(Server is running on port: ${PORT})

        3
  •  -1
  •   Diwas Shrestha    2 年前

    它只有在你使用背包的情况下才有效,在我的Mac Pro上,它位于tab键上方。

    如果您使用单引号或双引号,它将不起作用!