简体   繁体   English

JavaScript 中的 ${value} 不起作用

[英]${value} in JavaScript doesn't work

I do have a very simple use case:我确实有一个非常简单的用例:

it('Formatting with ${}', () => {
   const value = 1
   const info = 'the result is: ${value}'

   assert.equal(info, 'the result is: 1')
})

But it doesn't work and I can't see why.但它不起作用,我不明白为什么。 It's using ES6 because arrow function works.它使用 ES6,因为箭头功能有效。 I tried let instead of const, even var.我尝试了 let 而不是 const,甚至是 var。 Nothing works.没有任何效果。

Can anybody help?有人可以帮忙吗?

Best regards, Torsten最好的问候,托斯滕

You have to use back-ticks ( ` ) instead of single quote ( ' ) or double quote ( " ) to use string interpolation您必须使用反引号 ( ` ) 而不是单引号 ( ' ) 或双引号 ( " ) 才能使用字符串插值

it('Formatting with ${}', () => {
    const value = 1
    const info = `the result is: ${value}`

    assert.equal(info, 'the result is: 1')
})

Do

`the result is: ${value}`

instead of 'the result is: ${value}' .而不是'the result is: ${value}'

This happens because in JavaScript there's a concept of Template literals which let's user evaluate embedded expressions .发生这种情况是因为在 JavaScript 中有一个模板文字的概念,它可以让用户评估嵌入的表达式 You can read more about it in the link provided.您可以在提供的链接中阅读有关它的更多信息。

Instead of 'result is: ${value}'而不是“结果是:${value}”

Please use Backticks请使用反引号

 const test = 'hello!' // Template Literal console.log(`testing: ${test}`)

If you dont know where Is the Backtick is Mostly near the Esc button如果您不知道反引号在哪里 主要在 Esc 按钮附近

Hopes this help希望这有帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM