![](/img/trans.png)
[英]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.