警报返回不止一次

时间:2014-12-22 21:43:45

标签: javascript

我正在学习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);

2 个答案:

答案 0 :(得分:3)

这个功能没有问题,我猜你不小心把它叫了两次? 请检查一下,这个功能无法提醒两次。你两次打电话一定是犯了错误。

答案 1 :(得分:0)

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

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

  }  
}