簡體   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