gpt4 book ai didi

javascript - 将 if 语句转换为 switch 语句

转载 作者:行者123 更新时间:2023-11-30 13:51:44 25 4
gpt4 key购买 nike

我需要将函数中的 if 语句转换为 switch 语句进行赋值。该功能需要做的是在用户按下提交按钮时让用户输入成为显示的列表项。当输入的数量等于 5 时,它会显示“感谢您的建议。”

我将原始 if 语句作为注释包含在内。

我不确定从这里到哪里才能使它的工作方式与 if 语句相同。

    <article>
<div id="results">
<ul>
<li id="item1"></li>
<li id="item2"></li>
<li id="item3"></li>
<li id="item4"></li>
<li id="item5"></li>
</ul>
<p id="resultsExpl"></p>
</div>
<form>
<fieldset>
<label for="toolBox" id="placeLabel">
Type the name of a tool, then click Submit:
</label>
<input type="text" id="toolBox" />
</fieldset>
<fieldset>
<button type="button" id="button">Submit</button>
</fieldset>
</form>
</article>
<script>
// global variables
var i=1;
var listItem = "";
// function to add input to list
function processInput()
{
/*
if (i<=5)
{
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
if (i==5)
{
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
}
i++;
}
*/
switch (i) {
case 5:
document.getElementById("resultsExpl").innerHTML = "Thanks for your suggestions.";
break;
case default:
listItem = "item" + i;
document.getElementById(listItem).innerHTML = document.getElementById("toolBox").value;
document.getElementById("toolBox").value = "";
i++;
}
}
// adds backward compatible event listener to Submit button
var submitButton = document.getElementById("button");
if (submitButton.addEventListener) {
submitButton.addEventListener("click", processInput, false);
} else if (submitButton.attachEvent) {
submitButton.attachEvent("onclick", processInput);
}
</script>

最佳答案

我将引用 Douglas Crockford 来自:Javascript the good parts

The switch statement is a competent feature. Like most competent features, it has loads of problems with it- the requirement of using break after every statement within a case, procedural control flow, out-of-place syntax, handling of code blocks, and much much more! Unfortunately, solving these problems would require us to rewrite how it operates at the core and the spec would entirely change, which, for a language like JavaScript, would create massive backwards compatibility issues.

底线:坚持 if/else if/else 语句。

关于javascript - 将 if 语句转换为 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58108081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com