如果重量太大或太小,我的代码不会发出警报

My code wont alert if the weight is too large or too small

获得体重后,我希望警报为 "too large" 或 "too small",具体取决于提示用户输入的数字。我可以获得代码来询问体重,但之后没有其他警报。

function calculateWeightInNewtons(mass) {

weight = mass * 9.8;
return weight;

if (weight > 500){
    alert("Weight is too big");
}
if (weight < 100){
    alert("weight is too small");
}



}

var massInKilograms = parseFloat(prompt("What is the object's mass in kilograms? "));
calculateWeightInNewtons(massInKilograms);

这是因为您return正在从函数中调用。下面的代码没有执行。如果您需要 return 一个值,请确保在提醒消息后执行此操作。但理想情况下,为了使函数更简洁,它应该只做一件事。所以最好把功能分解成不同的功能。

function calculateWeightInNewtons(mass) {
  weight = mass * 9.8;
  return weight;
}

function alertWeight(weight) {
  if (weight > 500){
      alert("Weight is too big");
  }
  if (weight < 100){
      alert("weight is too small");
  }
}

var massInKilograms = parseFloat(prompt("What is the object's mass in kilograms? "));
var weight = calculateWeightInNewtons(massInKilograms);
alertWeight(weight);