英文:
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 ? "The value is same" : ""}
${"a" === "b" ? "" : "Different letters"}`;
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 ? "The value is same\n" : ""}${"a" === "b" ? "" : "Different letters"}`;
console.log(toolTipText);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论