可以'找不到错误

Can't find error

本文关键字:找不到 错误 可以      更新时间:2023-11-10

我不知道为什么不起作用,控制台没有说有错误,但当它应该第二次显示"提示"时,它就不起作用了。这是代码:

const Fanta = 250,Sprite = 250,Cola = 250,Dirol = 450,Snickers = 300,Lays = 800;
var a = prompt("1:Fanta = 250, 2:Sprite = 250, 3:Coca Cola = 250, 4:Dirol = 450, 5:Snickers = 300, 6:Lays = 800");
function math()
{
if(a == 1)
{
alert("You chose Fanta");
var money = prompt("Put money in");
alert("You put in " + money)
if(money >= 250)
{
    alert("You just purchased Fanta! Take back" + money - Fanta);
}
}
}

您将一些代码封装在未被调用的函数math()中。一种解决方案是打开包装(删除功能):

const Fanta = 250,
  Sprite = 250,
  Cola = 250,
  Dirol = 450,
  Snickers = 300,
  Lays = 800;
var a = prompt("1:Fanta = 250, 2:Sprite = 250, 3:Coca Cola = 250, 4:Dirol = 450, 5:Snickers = 300, 6:Lays = 800");

  if (a == 1) {
    alert("You chose Fanta");
    var money = prompt("Put money in");
    alert("You put in " + money)
    if (money >= 250) {
      alert("You just purchased Fanta! Take back" + money - Fanta);
    }
  }

另一种解决方案是调用函数math():

var a = prompt(...);
math();

您应该在分配给a之后调用它。当然,您的函数将使用a作为一个本质上的全局变量,这被认为是一种糟糕的做法,因此您可能需要对代码进行一点重构,以显式地将其传递给math()