function mathProb() {
var x = parseInt(prompt("Enter first integer", ""));
var y = parseInt(prompt("Enter the second integer", ""));
var operand = prompt("Enter type of operation", "");
if (operand == "+" || "add") {
var sum = x + y;
document.write("Your sum is " + sum);
} else if (operand == "-") {
var difference = x - y;
document.write("Your difference is " + difference);
} else if (operand == "*") {
var product = x * y;
document.write("Your product is " + product);
} else if (operand == "/") {
var quotient = x / y;
document.write("Your quotient is " + quotient);
} else {
document.write("Oops something went wrong");
}
}
好了开始我正在阅读一本关于JavaScript的书并且做得很好,我现在正在使用函数,并且在引入参数之前获取这些函数是否有人可以用简单的方式解释参数是什么?
为什么在命名为function mathProb()
和function mathProb(x,y,operand)
?
关于上一个问题的第三个问题是为什么当我在html中调用该函数时
(<input type="button" value="Calculator" onclick="mathProb()"/>
)
即使名为mathProb()
,我也必须使用mathProb(x,y,operand)
。如果我使用该名称来调用它就无法工作。请帮帮忙?
答案 0 :(得分:1)
首先,行:
if(operand=="+"||"add")
永远是 true ,因为表达式"add"
将始终返回true-ish值。你可能想要使用:
if(operand=="+" || operand=="add")
关于参数的问题可能是一个非常广泛的主题。基本上,参数是函数的赋值,因此可以将函数推广到可以处理任何数据。例如,如果您想编写一个可以添加两个数字的函数,该函数必须知道要添加的两个两个数字。这些数字将作为参数提供:
function add(x, y)
{
return x + y; // x and y are variables known within this function
}
然后你可以这样调用你的函数:
var oneplusone = add(1, 1); // Adds 1 and 1
使用这些知识,您可以重写代码:
function mathProb(x, y, operand)
{
// No need for var x, etc as these can now be passed in..
}
然后调用你的函数:
mathProb(
parseInt(prompt("Enter first integer","")), // This is x
parseInt(prompt("Enter the second integer","")), // This is y
prompt("Enter type of operation","") // This is operand
);
请注意,您可以仍然在没有参数的情况下调用您的函数mathProb
:
mathProb();
...如果你真的想。 JavaScript 允许这样做(与许多其他语言不同)。但是,在您的函数中,变量x
,y
和operand
将未定义,如果您不考虑该变量,可能会导致意外结果。< / p>
答案 1 :(得分:0)
您需要调用并传递mathProb(1,2,'+')
HTML:
<input type="button" value="Calculator" onclick="mathProb(1,2,'+')"/>
Javacript:
function mathProb(x,y,operand)
{
//var x = parseInt(prompt("Enter first integer",""));
//var y = parseInt(prompt("Enter the second integer",""));
//var operand = prompt("Enter type of operation","");
if(operand=="+"|| operand=="add")
{
var sum = x+y;
document.write("Your sum is " +sum);
}
else if(operand=="-")
{
var difference = x-y;
document.write("Your difference is " +difference);
}
else if(operand=="*")
{
var product = x*y;
document.write("Your product is " +product);
}
else if(operand=="/")
{
var quotient = x/y;
document.write("Your quotient is " +quotient);
}
else
{
document.write("Oops something went wrong");
}
}