【问题标题】:ECMAScript template literals like 'some ${string}' are not working像 \'some ${string}\' 这样的 ECMAScript 模板文字不起作用
【发布时间】:2022-08-01 12:21:37
【问题描述】:

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

例子

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

输出

${this.categoryName}
categoryElements: ${this.categoryElements}
  • 使用重音 ` 而不是单引号 \' 或双引号 \"

标签: javascript template-literals


【解决方案1】:

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 等中创建代码段。很容易认为反勾号是一个代码标记,然后在脑海中将其转换为单个勾号。谢谢,谢谢你。
  • “如果您使用的是 QWERTY 键盘” ...美国布局。一些 QWERTY 布局(例如 QWERTY JIS)不会在此处放置反引号。
【解决方案2】:

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

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

【讨论】:

  • 请注意,有许多不同的键盘布局!英式 QWERTY 布局具有 "shift + 2'` 有自己的键,不需要修饰符。
【解决方案3】:

它仅在您使用背包时才有效,在我的 Mac Pro 上,它是 Tab 键上方的 `。

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

【讨论】:

    【解决方案4】:

    我无法获得所需的输出。 我使用了单引号 ',这是不正确的,它正在打印相同的消息。

    反引号位于键盘中的 ~ 下方。 使用shift+~ 获取反引号

    希望能帮助到你。

    【讨论】:

      【解决方案5】:

      模板文字不要使用双引号/单引号 而是使用反引号

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

      更多信息请访问 Mdn 文档https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals

      【讨论】:

        【解决方案6】:

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

        【讨论】:

          【解决方案7】:

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

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

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

          【讨论】:

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