${}(美元符号和大括号)在 JavaScript 中的字符串中是什么意思

What does ${} (dollar sign and curly braces) mean in a string in JavaScript?

本文关键字:JavaScript 意思 是什么 字符串 美元 符号      更新时间:2023-09-26

我在这里或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

如上面的注释中所述,您可以在模板字符串/文本中包含表达式。例:

const one = 1;
const two = 2;
const result = `One add two is ${one + two}`;
console.log(result); // output: One add two is 3

还可以使用模板文本执行隐式类型转换。例:

let 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!

const firstName = 'Sachin';常量年龄 = 16警报( ${firstName} is ${age} years old

萨钦今年 16 岁