【问题标题】:ECMAScript template literals like 'some ${string}' are not working像 'some ${string}' 这样的 ECMAScript 模板文字不起作用
【发布时间】:2016-09-11 18:09:31
【问题描述】:

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

示例

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

输出

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

【问题讨论】:

  • 使用重音 ` 而不是单引号 ' 或双引号 "

标签: javascript template-literals


【解决方案1】:

只有在你使用背包的情况下才有效,在我的 Mac Pro 上是 Tab 键上方的 `。

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

【讨论】:

    【解决方案2】:

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

    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}`)
    

    【讨论】:

      【解决方案3】:

      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

      【讨论】:

      • 哇,你不会相信我花了多长时间才找到这个。令人难以置信的是,这是问题所在,尤其是反引号用于在 Markdown 等中创建代码段。很容易认为反勾号是一个代码标记,然后在脑海中将其转换为单个勾号。谢谢,谢谢。
      【解决方案4】:

      // 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

      【讨论】:

        【解决方案5】:

        1.) 添加与您的 app.js 和其他文件相同的文件夹级别的 .jshitrc

        2.) 将其放入新创建的文件 { "esversion": 6 }

        3.) 永远不要使用单引号 ' 使用反引号 `

        【讨论】:

        • 这个答案与问题有什么关系?
        猜你喜欢
        • 2022-08-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多