[英]Javascript enters if statement when the condition should evaluate false
我有一個問題,當條件應評估為false時,javascript輸入if語句。 我將JavaScript鏈接到HTML。 HTML將表單用作每個變量的輸入,當任何形式的輸入類型均未輸入任何內容時,javascript將輸出“ 0”。
當將5輸入initialVelocity ,將45輸入finalVelocity時 ,輸出為50 。
隨意取笑我的編碼風格,感謝所有答案!
function physicsFunction() {
var initialVelocity = document.getElementById('formInitialV').elements['initialVName'].value;
var finalVelocity = document.getElementById('formFinalV').elements['finalVName'].value;
var time = document.getElementById('formTime').elements['timeName'].value;
var acceleration = document.getElementById('formAcceleration').elements['accelerationName'].value;
var averageAcceleration = document.getElementById('formAvgAcceleration').elements['avgAccelerationName'].value;
var displacement = document.getElementById('formDisplacement').elements['displacementName'].value;
var averageVelocity = document.getElementById('formAvgVelocity').elements['avgVelocityName'].value;
if (initialVelocity !== undefined && acceleration !== undefined && time !== undefined) {
var finalVelocity = (initialVelocity + acceleration * time);
document.getElementById('paragraphOne').innerHTML = 'The final Velocity is about equal to: ' + finalVelocity +' m/s';
}}
要獲得真實的undefined
值,可以使用類似以下的函數:
function UndefinedIfEmpty(value) { if(value.trim() == "") { return undefined; } else { return value; } } // Use it: // var initialVelocity = UndefinedIfEmpty(document.getElementById('formInitialV').elements['initialVName'].value); // and so on console.log("`` is ", UndefinedIfEmpty("")); console.log("` ` is ", UndefinedIfEmpty(" ")); console.log("`12` is ", UndefinedIfEmpty("12"));
您甚至應該轉換為數字,以避免: initialVelocity + acceleration * time
=> "12" + "4" * 13
=> "12" + 52 => "1252"
(字符串串聯)。
function NumberOrUndefined(value) { value = value.trim(); if ( value == "" ) { return undefined; } else { return parseInt(value, 10); } } // 10 in parseInt to avoid octal convertion console.log("` ` is", NumberOrUndefined(" ")); console.log("12 is a ", typeof NumberOrUndefined("12"));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.