有没有一种方法可以强制JavaScript在警报框中返回负值?

时间:2018-12-20 03:50:49

标签: javascript

JavaScript返回X-Y,其中X和Y是实数,它们的和为负数,而不仅仅是负数。

我尝试使用

的if else语句
if (Math.sign(function)<0)
else

其中if语句在值前仅带有一个“-”以在数字前连接字符串“减号”,而else则仅是常规打印输出

function velocity_final(initial_velocity, acceleration, time)
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = initial_velocity + acceleration * time;
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

3 个答案:

答案 0 :(得分:7)

prompt始终返回字符串,而不是数字。即使此人输入了数字,也将是代表该数字的字符串,而不是数字本身。

您需要将prompt的结果转换为数字,然后才能对其进行加法运算。与字符串一起使用时,+是串联运算符,而不是加法运算符。

有些令人困惑的是,您实际上可以为此使用一元+

var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
var time = +prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');

答案 1 :(得分:2)

+运算符既可以是加法运算,也可以是字符串串联运算。当prompt框返回时,它会给您返回一个字符串。 String + number = string,因此它将两个值连接在一起(而不是相加)。要解决此问题,您可以使用单个+运算符将字符串转换为数字(如果需要,还可以加上一些括号)将字符串转换为数字,如下所示:

function velocity_final()
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = (+initial_velocity) + (+acceleration) * (+time);
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

console.log(velocity_final());

如果需要,您还可以在提示返回值后立即转换这些值。

PS:我删除了函数参数,因为您还是手动设置了它们而不是传入任何参数。如果最终确实传入了值而不是向用户询问它们,则需要将这些值重新添加到正确传递它们的功能声明。

答案 2 :(得分:1)

提示返回一个字符串。这样,由于串联,执行"1" +"-1"将导致"1-1""1" + "1"在打印输出中为何变成2的原因是Javascript如何自动尝试将字符串解析为数字,如果所评估的字符串包含一个字符,则将其串联起来。您需要显式转换数字。

您可以使用Number(),可以将每个字符串乘以1来自动转换它们,可以使用parseInt(),也可以在返回值之前使用+,如其他答案在这里。我将使用下面示例中提到的第一个。

function velocity_final()
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = Number(initial_velocity) + Number(acceleration) * Number(time);
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

velocity_final();