How can I do string interpolation in JavaScript?

前端 未结 19 3033
慢半拍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:14

    Expanding on Greg Kindel's second answer, you can write a function to eliminate some of the boilerplate:

    var fmt = {
        join: function() {
            return Array.prototype.slice.call(arguments).join(' ');
        },
        log: function() {
            console.log(this.join(...arguments));
        }
    }
    

    Usage:

    var age = 7;
    var years = 5;
    var sentence = fmt.join('I am now', age, 'years old!');
    fmt.log('In', years, 'years I will be', age + years, 'years old!');
    

提交回复
热议问题