2014-09-20 165 views
1

我试图做一个简单的一段JavaScript代码,当用户将在一个盒子的长度和宽度,以及计算机计算它们框的面积。我所做的是将函数参数分配给(长度,宽度),然后我做了两个变量,这些变量将分配给用户放入的长度和宽度。在用户输入长度和宽度后,我调用函数并将其参数分配给两个长度和宽度变量。接下来我做了一个确认部分,它将函数的最终结果显示出来。使用变量分配函数参数?

//Telling the computer what to do with the length and width. 
var area = function (length, width) { 
    return length * width; 
}; 

//Asking the user what the length and width are, and assigning the answers to the function. 
var l = prompt("What is the length of the box?"); 
var w = prompt("What is the width of the box?"); 
area(l, w); 

//Showing the end-result. 
confirm("The area is:" + " " + area); 

发生的是,最终的结果示出了

面积是:功能(长度,宽度){ 返回长度*宽度; \ }

因此,代码的最终结果正在显示等号右边的内容,就好像写了什么字符串一样。任何人都可以帮忙吗?

回答

0

您需要将结果分配给另一个变量:

var calculated_area = area(l, w); 

confirm("The area is: " + calculated_area); 

你看到什么是变量area包含的功能,而不是它返回值。

2

你所做的事是通过一个名为area到名为confirm该函数的功能。你想代替,传递的调用结果命名areaconfirm

confirm("The area is:" + area(l, w)); 

或可选择地命名的函数功能:

var result = area(l, w); 
confirm("The area is: " + result); 
相关问题