我在这里和MDN上都没有看到相关的内容。我确信我只是错过了某些东西。一定有一些关于此的文档。
从功能上看,它似乎允许您在字符串内嵌套一个变量而不使用+
运算符进行连接。我正在寻找有关此功能的文档。
示例:
var string = 'this is a string';
console.log(`Insert a string here: ${string}`);
我在这里和MDN上都没有看到相关的内容。我确信我只是错过了某些东西。一定有一些关于此的文档。
从功能上看,它似乎允许您在字符串内嵌套一个变量而不使用+
运算符进行连接。我正在寻找有关此功能的文档。
示例:
var string = 'this is a string';
console.log(`Insert a string here: ${string}`);
你在谈论模板字面量。
它们允许使用多行字符串和字符串插值。
多行字符串:
console.log(`foo
bar`);
// foo
// bar
字符串插值:
var foo = 'bar';
console.log(`Let's meet at the ${foo}`);
// Let's meet at the bar
console.log(\
Your array:\n ${arr.join('\n ')}`)` - T4NK3R如上方评论所述,您可以在模板字符串/文字中使用表达式。例如:
const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3
hey ${obj.name}
。 - Joel Hlet fruits = ["mango","orange","pineapple","papaya"];
console.log(`My favourite fruits are ${fruits}`);
// My favourite fruits are mango,orange,pineapple,papaya
它用于在字符串内引用变量:
let someVar = "World!"
console.log(`Hello ${someVar}`); // Output is Hello World!
它被用作变量插值 ${variable_name}
const firstName = 'Sachin';
const age = 16
alert(${firstName}今年${age}岁了
)
//Sachin今年16岁