[英]How to customize a string by variable in Javascript?
I want to print an errormessage using javascript in certain cases.在某些情况下,我想使用 javascript 打印错误消息。 The string is german and the start depends on a variable called
blfType
which can be "field", "line" or "block" and the string then would be "This field already has this prerequisite" if blfType
is field.字符串是德语,开头取决于名为
blfType
的变量,该变量可以是“字段”、“行”或“块”,如果blfType
是字段,则字符串将是“此字段已具有此先决条件”。 I tried to do that similiar as I would do it in python:我试着像在 python 中那样做:
alert("Das Feld"*(blfType == 'field') + "Die Zeile"*(blfType == 'line') + "Der Block"*(blfType == 'block')+" besitzt diese Vorraussetzung bereits");
But this would just print "NaN besitzt diese Vorraussetzung bereits"
.但这只会打印
"NaN besitzt diese Vorraussetzung bereits"
。 Is there any other way how I can do this in just one line or do I have to do create another Variable that takes the start of the sentence.有没有其他方法可以在一行中完成此操作,或者我是否必须创建另一个位于句子开头的变量。
In this case I would do this in python like that:在这种情况下,我会在 python 中这样做:
const gerblfType = "Feld" if blfType === "field" else "Zeile" if blfType === "line" else "Block"
But this is also not working.但这也行不通。 Is there a smooth way in Javascript to not do it like that:
Javascript 中是否有一种流畅的方法可以不这样做:
gerblfType = "Feld";
if(blfType == "line") gerblfType = "Zeile";
if(blfType == "block") gerblfType = "Block";
我实际上找到了解决您的第一个问题的方法:
alert("Das Feld".repeat(blfType == 'field') + "Die Zeile".repeat(blfType == 'line') + "Der Block".repeat(blfType == 'block')+" besitzt diese Vorraussetzung bereits");
Use switch
instead of if
s.使用
switch
而不是if
s。
let gerblfType;
switch (blfType) {
case 'line': gerblfType = 'Die Zeile'; break;
case 'block': gerblfType = 'Der Block'; break;
default: gerblfType = 'Das Feld'; break;
}
alert(`${gerblfType} besitzt diese Vorraussetzung bereits`);
Typical ways people would do it.人们会这样做的典型方式。
The if way如果方式
const foo = "two"; let bar = "default"; if(foo === "one") bar = "1"; else if(foo === "two") bar = "2"; console.log(bar);
With nested Ternary使用嵌套的三元
const foo = "two"; const bar = foo === "one" ? "1" : foo === "two" ? "2" : "default"; console.log(bar);
With an object有对象
const LOOK_UP = { one: "1", two: "2", default: "default" }; const foo = "two"; const bar = LOOK_UP[foo] || LOOK_UP.default; console.log(bar);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.