[英]Concatenate different variable if exist in JS
我想連接不同的變量(如果存在)並返回結果。 但是我需要用“-”分隔值,只返回有值的變量。
所以我有這個:
var test = "";
var test1 = "";
var test2 = "";
var test3 = "";
var checkTrue = "Rightt";
var checkFalse = "Wrong";
var checkWord = "Helloo";
var checkWord2 = "Bye";
if(checkTrue === "Right"){
test = "This is right"
} else {
test = "";
}
if(checkFalse === "Wrong"){
test1 = "This is wrong"
} else {
test1 = "";
}
if(checkWord === "Hello"){
test2 = "The word is hello"
} else {
test2 = "";
}
if(checkWord2 === "Bye"){
test3 = "The word is hello"
} else {
test3 = "";
}
var result = test + " - " + test1 + " - " + test2 + " -" + test3;
console.log(result);
所以我想我需要在我的 var 結果之前驗證是否存在不同的變量?
感謝您的幫助
實際結果:
- This is wrong - -The word is hello
預期結果:
This is wrong - The word is hello
對於任何你想要在字符串值之間使用分隔符的東西,我發現使用Array.prototype.join()
會更容易,它只會在實際值之間放置分隔符。
然后它變得更容易,因為你有一個可以連接的results
數組,只添加你想要的值而不是測試你不再需要的每個變量。
通過推送到一個數組,您也可以擺脫所有這些test
變量。
const results = []; const checkTrue = "Rightt"; const checkFalse = "Wrong"; const checkWord = "Helloo"; const checkWord2 = "Bye"; if (checkTrue === "Right") results.push("This is right") if (checkFalse === "Wrong") results.push("This is wrong") if (checkWord === "Hello") results.push("The word is hello") if (checkWord2 === "Bye") results.push("The word is hello") const result = results.join(" - "); console.log(result);
const test = ''; const test1 = 'This is wrong'; const test2 = ''; const test3 = 'The word is hello' const result = [test, test1, test2, test3].filter(value => value).join(' - '); console.log(result);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.