考虑以下代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了使用字符串拼接,还有其他方式将变量的值插入到字符串中吗?
考虑以下代码:
var age = 3;
console.log("I'm " + age + " years old!");
除了使用字符串拼接,还有其他方式将变量的值插入到字符串中吗?
虽然模板可能是您所描述的情况下最好的选择,但如果您拥有或希望将数据和/或参数以可迭代/数组形式使用,则可以使用String.raw
。
String.raw({
raw: ["I'm ", " years old!"]
}, 3);
使用数组作为数据,可以使用展开运算符:
const args = [3, 'yesterday'];
String.raw({
raw: ["I'm ", " years old as of ", ""]
}, ...args);
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
Show GRAPH of : AIP001-_sma
(在字符串1周围使用反引号,无法在此处显示)。 - Marcos