警报多次返回

Alert returning more than once

本文关键字:返回      更新时间:2023-09-26

我正在学习JS,我正在尝试解决编码挑战。 我假设在输入参数时有一个警报告诉用户发电机总数量和总瓦特。 问题是代码阅读器说我正在提醒不止一个。 我正在做什么使警报被多次调用? 这是我的第一次尝试:

function changePowerTotal(totalMW,genID,status,powerMW){
  if(typeof(status) == "on" || typeof(status) == "ON"){
    alert("Generator #"+genID+" is now on, adding "+powerMW+" MW, for a total of "+ (totalMW) +" MW!");
    return false;
  } else {
    if(totalMW == 0){
       alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (powerMW) +" MW!");
    } else {
       alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (totalMW - powerMW) +" MW!");
    }
    return false;
  }
}
changePowerTotal(0,2,"off",62);

我也试过这个:

function changePowerTotal(totalMW,genID,status,powerMW){
  var genStatus = "";
  if(status === "on"){
   genStatus = " is now on, adding "
   totalMW = totalMW + powerMW;
  } else {
   genStatus = " is now off, removing "
   totalMW = totalMW - powerMW;
  }
  alert("Generator #"+genID+genStatus+powerMW+" for a total of "+totalMW+" MW!");
}
changePowerTotal(142,2,"off",62);

函数没有问题,我猜你不小心叫了两次?请检查您是否这样做了,此功能无法发出两次警报。你一定犯了一个错误,称它两次。

谢谢大家的帮助。 我找到了解决方案,这里是:

function changePowerTotal (totalMW, genID, genStatus,genMW){
  var curStatus = " ";
  var sumMW = 0;
  if(genStatus === "off"){
   curStatus = " is now "+genStatus+", removing ";
   alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+totalMW+"MW!");
   return totalMW + genMW
  } else {
    curStatus = " is now "+genStatus+", adding ";
    sumMW = genMW + totalMW;
    alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+(totalMW + genMW)+"MW!");
    return totalMW + genMW
  }  
}