JavaScript equivalent of Python's format() function?

前端 未结 17 1980
慢半拍i
慢半拍i 2020-12-13 08:42

Python has this beautiful function to turn this:

bar1 = \'foobar\'
bar2 = \'jumped\'
bar3 = \'dog\'

foo = \'The lazy \' + bar3 + \' \' + bar2 \' over the \'         


        
17条回答
  •  醉梦人生
    2020-12-13 08:55

    tl;dr

    foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
    

    Why template strings alone aren't enough

    ES6 template strings provide a feature quite similar to pythons string format. However, you have to know the variables before you construct the string:

    var templateString = `The lazy ${bar3} ${bar2} over the ${bar1}`;
    

    Why format?

    Python's str.format allows you to specify the string before you even know which values you want to plug into it, like:

    foo = 'The lazy {} {} over the {}'
    
    bar1 = 'foobar'
    bar2 = 'jumped'
    bar3 = 'dog'
    
    foo.format(bar3, bar2, bar1)
    

    Solution

    With an arrow function, we can elegantly wrap the template string for later use:

    foo = (a, b, c) => `The lazy ${a} ${b} over the ${c}`
    
    bar1 = 'foobar';
    bar2 = 'jumped';
    bar3 = 'dog';
    
    foo(bar3, bar2, bar1)
    

    Of course this works with a regular function as well, but the arrow function allows us to make this a one-liner. Both features are available in most browsers und runtimes:

    • Can I use template literals?
    • Can I use arrow functions?

提交回复
热议问题