我正在尝试编写一段简单的 JavaScript 代码,用户在其中输入一个盒子的长度和宽度,然后计算机会为他们计算盒子的面积。我所做的是将函数参数分配给 (length, width),然后我创建了两个变量,这两个变量将分配给用户输入的长度和宽度。用户输入长度和宽度后,我调用该函数并将其参数分配给两个长度和宽度变量。接下来我做了一个确认部分,获取函数的最终结果并显示它。
//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);
发生的事情是,最终结果显示
面积为:函数(长,宽){ 返回长度 * 宽度;\
所以代码的最终结果是显示等号右边的东西,就好像那里写的是一个字符串。有人可以帮忙吗?
最佳答案
您所做的是将名为area
的函数传递给名为confirm
的函数。相反,您想要将 调用 名为 area
的函数的结果传递给名为 confirm
confirm("The area is:" + area(l, w));
或者:
var result = area(l, w);
confirm("The area is: " + result);
关于javascript - 使用变量分配函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25953190/