2013-12-09 61 views
0
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的书,并且一直做得很好,我现在正在使用函数,直到参数被引入才能解释什么一个参数明确简单的方式?JavaScript的帮助(这是一个非常简单的初学者)

此功能为什么在命名为function mathProb()function mathProb(x,y,operand)时工作?

和关闭前一个的第三个问题就是为什么当我调用该函数在HTML (<input type="button" value="Calculator" onclick="mathProb()"/>) 我不得不使用mathProb()即使其命名为mathProb(x,y,operand)。如果我用这个名字叫它不会工作。请帮忙?

+3

请试着总结一下标题您qeustion,以使其更具描述性的问题。 –

回答

1

首先,该行:

if(operand=="+"||"add") 

永远是真实,作为表达"add"总是返回真值十岁上下。您可能的意思是使用:

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,yoperand将为未定义如果您不考虑此问题,这可能会导致意外的结果。

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"); 
    } 
}