[英]Why does the following program return incorrect boolean values for some inputs?
[英]Why does the order of Boolean values affect this program?
我创建了一个基本程序,其中用户输入变成了提交警报。 我不知道为什么如果我在if / else语句中使用false而不是true作为第一个条件时,该程序只能按预期工作。 我敢肯定这是非常基本的,但是我没有找到任何相关的东西。 经过长时间的搜索,我决定发布问题。 任何答案将不胜感激。
HTML:
<form id="greetingForm">
<input type="text" name="userInput" id="userInput"/>
<input type="submit" value="click" id="submit"/>
</form>
损坏的脚本:
function output(){
var input = document.getElementById('userInput').value;
if(input == true){
alert(input);
}else{
alert('Say something!');
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
工作脚本:
function output(){
var input = document.getElementById('userInput').value;
if(input == false){
alert('Say something!');
}else{
alert(input);
}
}
function init(){
var greetingForm = document.getElementById('greetingForm');
greetingForm.onsubmit = output;
}
window.onload = init;
输入的变量永远不会等于布尔值true,因为它是一个字符串。 尝试将其更改为:
function output(){
var input = document.getElementById('userInput').value;
if(input != ""){
alert(input);
}else{
alert('Say something!');
}
}
为了阐明ferd tomale的答案,这是“奇怪”类型转换案例之一,其中对等于等于true
检查与对等于false
检查的行为不同。
"" == false -> true
"a" == false -> false, but
"" == true -> false
"a" == true -> false
您可以切换为使用类型安全比较运算符( ===
, !==
),它们的行为更具可预测性,但是您必须自己将值转换为正确的类型。 或者,当您使用==
或!=
时,您可以学习JS自动类型转换的怪癖。
因为您的输入是字符串。 并且string == true将为false 。
您可以设置断点来检查它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.