如何在JavaScript字符串中插入变量? [英] How to insert variables in JavaScript strings?
问题描述
在JavaScript中的字符串中插入变量的最佳方法是什么?我猜这不是这个:
What's the best way to do insert variables in a string in JavaScript? I'm guessing it's not this:
var coordinates = "x: " + x + ", y: " + y;
在Java中, String
s是不可变的,做上面这样的事情会不必要地创建并扔掉 String
s。 Ruby是类似的,有一个很好的方法来做上述事情:
In Java, String
s are immutable and doing something like the above would unnecessarily create and throw away String
s. Ruby is similar and has a nice way of doing the above:
coordinates = "x: #{x}, y: #{y}"
JavaScript有类似的东西吗?
Does something similar exist for JavaScript?
推荐答案
在ES6中作为模板字符串引入
Introduced in ES6 as "template strings"
MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
MDN docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const name = "Nick"
const greeting = `Hello ${name}` // "Hello Nick"
这篇关于如何在JavaScript字符串中插入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!