How can I do string interpolation in JavaScript?

前端 未结 19 2502
慢半拍i
慢半拍i 2020-11-21 07:54

Consider this code:

var age = 3;

console.log(\"I\'m \" + age + \" years old!\");

Are there any other ways to insert the value of a variabl

相关标签:
19条回答
  • 2020-11-21 08:25

    Since ES6, if you want to do string interpolation in object keys, you will get a SyntaxError: expected property name, got '${' if you do something like:

    let age = 3
    let obj = { `${age}`: 3 }
    

    You should do the following instead:

    let obj = { [`${age}`]: 3 }
    
    0 讨论(0)
提交回复
热议问题