考虑下面的代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了字符串连接之外,还有其他方法可以将变量的值插入到字符串中吗?
考虑下面的代码:
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'));
其他回答
我可以给你们举个例子:
函数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'));
警告:避免任何不允许您转义其自己的分隔符的模板系统。例如,使用此处提到的supplant()方法将无法输出以下内容。
“多亏了我的年龄变量,我才3岁。”
简单的插值可能适用于小型的自包含脚本,但通常会出现这种设计缺陷,限制任何重要的使用。老实说,我更喜欢DOM模板,比如:
<div> I am <span id="age"></span> years old!</div>
$('#age').text(3)
另外,如果你只是厌倦了字符串连接,总有替代语法:
var age = 3;
var str = ["I'm only", age, "years old"].join(" ");
你可以很容易地使用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}));
试试sprintf库(一个完整的开源JavaScript sprintf实现)。例如:
vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);
Vsprintf接受一个参数数组并返回一个格式化的字符串。