【发布时间】:2019-07-03 09:24:54
【问题描述】:
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)?
但即便如此,它仍然有效
【问题讨论】:
-
=是赋值,而不是比较,你的if(a = 1)实际上并没有测试任何东西,它总是会实现 -
平等检查
a == b会,如果a 和b 的类型不同,type coercion(转换)为你。身份检查a === b也会比较类型,并且仅在值和类型都匹配时才返回 true。 -
if ("one" == "one") 比较字符串 if ("one" == one ) 是否抛出错误???
-
即使 1 被认为是 "1" ;它会像 ("1"==1) 那样比较 --> 会怎么样??
标签: javascript html function if-statement