如何在JavaScript中进行字符串插值?

796

考虑以下代码:

var age = 3;

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

除了使用字符串拼接,还有其他方式将变量的值插入到字符串中吗?


7
你可以查看 CoffeeScript:http://coffeescript.org/。 - dennismonsewicz
2
正如其他人所指出的那样,你正在使用的方法确实是最简单的方法。我很想能够在字符串内引用变量,但在JavaScript中,你需要使用连接(或其他查找/替换方法)。像你和我这样的人可能对PHP有点太依赖了。 - SikoSoft
4
使用Underscore.js template - Jahan Zinedine
3
连接不等同于插值,用户询问如何执行插值。我认为Lev最终提供了答案,即在JS原生中没有办法做到这一点。我不明白为什么这不是一个真正的问题。 - gitb
5
如果我被允许回答,现在有一种解决方案可供新的解释器使用(2015年的FF和Chrome已经支持):https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings。例如,``Show GRAPH of: ${fundCode}-${funcCode}`` 将给我 Show GRAPH of : AIP001-_sma (在字符串1周围使用反引号,无法在此处显示)。 - Marcos
显示剩余6条评论
22个回答

0

虽然模板可能是您所描述的情况下最好的选择,但如果您拥有或希望将数据和/或参数以可迭代/数组形式使用,则可以使用String.raw

String.raw({
  raw: ["I'm ", " years old!"]
}, 3);

使用数组作为数据,可以使用展开运算符:

const args = [3, 'yesterday'];
String.raw({
  raw: ["I'm ", " years old as of ", ""]
}, ...args);

0
let age = 3;

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

console.log(`I'm ${age} years old`); //should work fine

const btn = `<input type='buttong' onclick='myFunction(${age})'>`;// in this case it will look for a variable named 3

const btn = `<input type='buttong' onclick='myFunction("${age}")'>`;// in this case value of age will be passed to your function

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接