考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
当前回答
let age = 3;
console.log(`I'm ${age} years old!`);
你可以使用反撇号' '和ES6模板字符串
其他回答
你可以很容易地使用ES6模板字符串,并使用任何可用的transpilar(如babel)编译到ES5。
const age = 3;
console.log(`I'm ${age} years old!`);
http://www.es6fiddle.net/im3c3euc/
你可以使用Prototype的模板系统,如果你真的想用大锤敲开一个坚果:
var template = new Template("I'm #{age} years old!");
alert(template.evaluate({age: 21}));
从ES6开始,如果你想在对象键中做字符串插值,你会得到一个SyntaxError: expected属性名,得到'${'如果你做这样的事情:
let age = 3
let obj = { `${age}`: 3 }
你应该做以下事情:
let obj = { [`${age}`]: 3 }
试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
Vsprintf接受一个参数数组并返回一个格式化的字符串。
扩展Greg Kindel的第二个答案,你可以写一个函数来消除一些样板文件:
var fmt = {
join: function() {
return Array.prototype.slice.call(arguments).join(' ');
},
log: function() {
console.log(this.join(...arguments));
}
}
用法:
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!');