//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>
对不起,我已经读过,如果不是序列,则主要优势是可以忽略break语句并执行多个块。我想在我的case(true)代码中执行多个块。但是我发现这个简单的代码有问题。
非常抱歉,您能否使用switch(true)解释部分代码的问题? 谢谢!
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);
}
答案 0 :(得分:2)
没有case
的{{1}}不会重新评估下一个break
的相等性,而只是无条件地运行称为fallthrough的块。我怀疑这就是您想要的。改为使用多个连续的case
语句(而不是if
链)-如果您不关心日志语句,则可以采用if-else
方法。
第二,records2
创建一个新数组,它不会通过追加目标来对其进行突变。有关各种解决方案,请参见How to append something to an array?或How to extend an existing JavaScript array with another array, without creating a new array。
答案 1 :(得分:-1)
您应该看一下价差运算符:
var records = [...recentlyCompleted, ...upcomingActivities, ..decisionsRequired]
您的records
和records2
总是一样。