function runif() {
let a = document.getElementById('test').value;
if (a == 1) {
console.log("works");
}
}
function runswitch() {
let a = document.getElementById('test').value;
switch (a) {
case 1:
console.log("working");
break;
default:
break;
}
}
function runswitchOne() {
let a = parseInt(document.getElementById('test').value);
switch (a) {
case 1:
console.log("working");
break;
default:
break;
}
}
<form action="">
<input type="text" id="test">
<input type="button" onclick="runif()" value="click to check if">
<input type="button" onclick="runswitch()" value="click to check without parseInt">
<input type="button" onclick="runswitchOne()" value="click to check with parseInt">
</form>
这是我用一个文本输入和两个按钮创建的表单。
其中 if 语句识别输入并执行操作
但是在 switch 我必须让它解析才能识别
我不明白为什么它有效?我知道文本输入会引起刺痛,但如果是这样,if() 语句如何在不解析的情况下工作?
通常我们使用 if(a == "1") 来比较字符串而不是 if(a==1)?
但即便如此它也能工作
switch case进行严格比较(检查value和type)。
元素的值是字符串类型。内部 switch case值是int类型并且不匹配。因此,如果不进行转换,您的代码将无法工作。
但是当使用时a == 1
只检查值而不检查类型并"1" == 1
评估为true。如果您进行严格比较(例如,===
),则"1" === 1
计算结果为false,因为在这种情况下,虽然值相等但类型不相等。
以下将起作用:
switch (a) {
case "1":
.....
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句