//JavaScript:
function concatArrays() {
var recentlyCompleted = ["rc1", "rc2"];
var upcomingActivities = [];
var decisionsRequired = [];
var records = [];
switch(true) {
case (recentlyCompleted.length >0):
records.concat(recentlyCompleted);
console.log("recentlyCompleted.length >0");
console.log(records);
case (upcomingActivities.length >0):
records.concat(upcomingActivities);
console.log("upcomingActivities.length >0");
console.log(records);
case (decisionsRequired.length >0):
records.concat(decisionsRequired);
console.log("decisionsRequired.length >0");
console.log(records);
break;
}
document.getElementById("demo").innerHTML = JSON.stringify(records);
var records2 = recentlyCompleted.concat(upcomingActivities).concat(decisionsRequired);
document.getElementById("demo2").innerHTML = JSON.stringify(records2);
}
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>switch(true)</title>
</head>
<body>
<p>Click the button to join arrays.</p>
<button onclick="concatArrays()">Try it</button>
<p id="demo"></p>
<p id="demo2"></p>
</body>
Sorry please I have read that the main advantage over the obvious if else if sequence is the ability to omit the break statement and execute more than one block. I wanted to execute more than one block in my case(true) code. But I see something wrong with this simple code.
I am very sorry but could you explain what's wrong with part of this code with switch(true) Thanks!
Execution more than one block:
Screenshot of the execution of the correct answer:
function concatArrays() {
var recentlyCompleted = ["rc1", "rc2"];
var upcomingActivities = [];
var decisionsRequired = [];
var records = [];
switch (true) {
case (recentlyCompleted.length > 0):
records = records.concat(recentlyCompleted);
console.log("recentlyCompleted.length >0");
console.log(records);
case (upcomingActivities.length > 0):
records = records.concat(upcomingActivities);
console.log("upcomingActivities.length >0");
console.log(records);
case (decisionsRequired.length > 0):
records = records.concat(decisionsRequired);
console.log("decisionsRequired.length >0");
console.log(records);
break;
}
document.getElementById("demo").innerHTML =
JSON.stringify(records);
var records2 = recentlyCompleted
.concat(upcomingActivities)
.concat(decisionsRequired);
document.getElementById("demo2").innerHTML =
JSON.stringify(records2);
}