我有一个问题,当条件应该评估为false时,javascript进入if语句。我有一个链接到HTML的JavaScript。 HTML使用表单作为每个变量的输入,当没有输入任何表单输入类型时,javascript输出“0”。
initialVelocity 时输入 5 , finalVelocity输入 45 输出 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';
}}
答案 0 :(得分:0)
要获得真实的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"));