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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35835362/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 18:16:10  来源:igfitidea点击:

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

javascriptstringvariablesconcatenation

提问by Darren Joy

I haven't seen anything here or on MDN. I'm sure I'm just missing something. There's got to be some documentation on this somewhere?

我在这里或 MDN 上都没有看到任何东西。我确定我只是错过了一些东西。某处必须有一些关于此的文档?

Functionally, it looks like it allows you to nest a variable inside a string without doing concatenation using the +operator. I'm looking for documentation on this feature.

从功能上讲,它似乎允许您将变量嵌套在字符串中,而无需使用+运算符进行连接。我正在寻找有关此功能的文档。

Example:

例子:

var string = 'this is a string';

console.log(`Insert a string here: ${string}`);

回答by Rick Runyon

You're talking about template literals.

你在谈论模板文字

They allow for both multiline strings and string interpolation.

它们允许多行字符串和字符串插值。

Multiline strings:

多行字符串:

console.log(`foo
bar`);
// foo
// bar

String interpolation:

字符串插值:

var foo = 'bar';
console.log(`Let's meet at the ${foo}`);
// Let's meet at the bar

回答by Joel H

As mentioned in a comment above, you can have expressions within the template strings/literals. Example:

正如上面的评论中提到的,您可以在模板字符串/文字中使用表达式。例子:

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