Usage of the backtick character (`) in JavaScript

后端 未结 9 2151
囚心锁ツ
囚心锁ツ 2020-11-22 00:51

In JavaScript, a backtick seems to work the same as a single quote. For instance, I can use a backtick to define a string like this:

var s         


        
9条回答
  •  遇见更好的自我
    2020-11-22 01:34

    The good part is we can make basic maths directly:

    let nuts = 7
    
    more.innerHTML = `
    
    

    You collected ${nuts} nuts so far!
    Double it, get ${nuts + nuts} nuts!! `

    It became really useful in a factory function:

    function nuts(it){
      return `
        You have ${it} nuts! 
    Cosinus of your nuts: ${Math.cos(it)}
    Triple nuts: ${3 * it}
    Your nuts encoded in BASE64:
    ${btoa(it)} ` } nut.oninput = (function(){ out.innerHTML = nuts(nut.value) })

    NUTS CALCULATOR

提交回复
热议问题