你必须原谅我,我是JavaScript新手......就像几个星期新的一样.无论如何,我使用JavaScript创建了一个代码来生成两个随机数,要求添加它们,并根据用户响应给出"那是正确的/那是不正确的"答案.我想将其他符号( - ,*,/)添加到等式中,并决定尝试在数组中执行此操作.这是我到目前为止:
<head>
<meta charset="utf-8" />
<title>Math Games</title>
</head>
<body>
<script>
var Answer;
var numbers=new Array();
var signs=new Array();
var Signs2=new Array();
var SignNoQuote=new Array();
numbers[0]=(Math.floor(Math.random() * 10 + 1));
numbers[1]=(Math.floor(Math.random() * 10 + 1));
signs[0]="+";
signs[1]="-";
signs[2]="*";
signs[3]="/";
SignNoQuote[0]="+";
SignNoQuote[1]="-";
SignNoQuote[2]="*";
SignNoQuote[3]="/";
Signs2[0]=(Math.floor(Math.random() * 4));
Answer=window.prompt("What is " + numbers[0] + signs[Signs2[0]] + numbers[1] + "?");
if(Answer==numbers[0] + SignNoQuote[Signs2[0]] + numbers[1])
{
window.alert("That's Correct!");
}
else
{
window.alert("That is Incorrect");
}
</script>
<a href="file:///E:/ECS/Legitimate%20Work/mathtest.html">Refresh</a>
</body>
Run Code Online (Sandbox Code Playgroud)
它正确地问了这个问题,但是当给出正确的答案时,它说它是不正确的.我尝试从"SignNoQuote"数组的值中删除引号,希望它可以工作,但是当它以这种方式运行时,脚本都不会运行,调试器声称它是语法错误?我做错了什么,我该如何解决?
如果你想要一个特定于你的用例的东西,这将很好地工作:
//A mapping from the symbol for an operation to
//the function that executes it.
var opFunction = {
"+": function (x, y) { return x + y; },
"-": function (x, y) { return x - y; },
"*": function (x, y) { return x * y; },
"/": function (x, y) { return x / y; }
};
//Gets the operation symbol.
var op = SignNoQuote[Signs2[0]];
//Looks up the function for the operation,
//then calls it with your numbers as operands.
var result = opFunction[op](numbers[0], numbers[1]);
Run Code Online (Sandbox Code Playgroud)
但是,如果您需要一些评估数学表达式的通用目的,Brad的答案将提供您所需要的.