考虑下面的代码:

var age = 3;

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

除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?


当前回答

我可以给你们举个例子:

函数fullName(first, last) { let fullName = first + " " + last; 返回fullName; } 函数fullNameStringInterpolation(first, last) { let fullName = ' ${first} ${last} '; 返回fullName; } console.log('Old School: ' + fullName('Carlos', 'Gutierrez')); console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));

其他回答

试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

Vsprintf接受一个参数数组并返回一个格式化的字符串。

你可以使用Prototype的模板系统,如果你真的想用大锤敲开一个坚果:

var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));

我可以给你们举个例子:

函数fullName(first, last) { let fullName = first + " " + last; 返回fullName; } 函数fullNameStringInterpolation(first, last) { let fullName = ' ${first} ${last} '; 返回fullName; } console.log('Old School: ' + fullName('Carlos', 'Gutierrez')); console.log('New School: ' + fullNameStringInterpolation('Carlos', 'Gutierrez'));

Douglas Crockford的remedy JavaScript包含一个String.prototype.supplant函数。它短小,熟悉,易于使用:

String.prototype.supplant = function (o) {
    return this.replace(/{([^{}]*)}/g,
        function (a, b) {
            var r = o[b];
            return typeof r === 'string' || typeof r === 'number' ? r : a;
        }
    );
};

// Usage:
alert("I'm {age} years old!".supplant({ age: 29 }));
alert("The {a} says {n}, {n}, {n}!".supplant({ a: 'cow', n: 'moo' }));

如果你不想改变String的原型,你总是可以把它调整成独立的,或者把它放在其他的名称空间里,等等。

从ES6开始,如果你想在对象键中做字符串插值,你会得到一个SyntaxError: expected属性名,得到'${'如果你做这样的事情:

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

你应该做以下事情:

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