在模板文字中使用多个三元运算符时的多行文本

huangapple go评论69阅读模式
英文:

Multiline text when using multiple ternary operators in Template literals

问题

我想使用单个模板文字中的多个三元运算符创建多行文本。

例如,在上面的代码中,我想在一行中显示“The value is same”,在下一行显示“Different letters”。然而,它们都在同一行中。我基本上是根据条件在文本中添加行。

如何实现?
英文:

I want to create multiline text using multiple ternary operators within a single Template literal.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const toolTipText = `${2 * 5 === 10 ? &quot;The value is same&quot; : &quot;&quot;}
  ${&quot;a&quot; === &quot;b&quot; ? &quot;&quot; : &quot;Different letters&quot;}`;

console.log(toolTipText);

<!-- end snippet -->

For example, in the code above, I want The value is same in one line & Different letters in the next line. However, they are both in the same line. I am basically trying to add lines on text based on conditions.

How to achieve it?

答案1

得分: 0

尝试在三元表达式中的The value is same后添加\n(换行字符的转义序列)。这样,只有在需要显示两行不同的行时才会显示一个新行:

const toolTipText = `${2 * 5 === 10 ? "The value is same\n" : ""}${"a" === "b" ? "" : "不同的字母"}`;
console.log(toolTipText);
英文:

Try adding \n (the escape sequence for a newline character) after The value is same in the ternary expression. This way, a new line will only show when there are two different lines that need to be shown:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const toolTipText = `${2 * 5 === 10 ? &quot;The value is same\n&quot; : &quot;&quot;}${&quot;a&quot; === &quot;b&quot; ? &quot;&quot; : &quot;Different letters&quot;}`;
console.log(toolTipText);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月29日 12:37:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354705.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定