繁体   English   中英

使用变量分配功能参数?

[英]Assigning function parameters using variables?

我正在尝试编写一个简单的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);

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

var calculated_area = area(l, w);

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

您看到的是变量area包含函数,而不是它返回的值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM