[英]Return statement not changing variable on global scope
我正在使用類似於真實計算器的用戶界面編寫計算器程序。 一切都進行得很好(對於xD而言,這對我來說是不尋常的),直到我需要從一個函數返回多個值為止(我在另一篇文章中讀到,這可以使用數組來完成)。 我還沒有將這些值返回到任何特定的位置,所以我認為它們只是被發送到全局范圍,並且到目前為止,它已經與其他函數(如updateDisplay()
。 但是,當我嘗試從operationClick()
返回returnValue
,它不會將更改發送到函數外部。
這是我的代碼的一些片段(希望如此,以便您能發現我在做錯什么):
returnValue = [false, undefined];
numberArray = new Array;
function operationClick(operation, concat, returnValue) {
if (operation == "equals") {
concatComplete = returnValue[1] + concat;
$('.screen_text').html(Number(concatComplete));
}
else if (operation == "add") {
returnValue = [true, concat + "+"];
console.log(returnValue); // The new value is correct here but not anywhere else :(
}
return returnValue; // Something goes wrong here!
}
function updateDisplay(array) {
concat = array.join("");
$('.screen_text').html(concat);
return concat
}
function numberClick(number, returnValue) {
if (returnValue[0] == true) {
// This should run once operationClick() else if statement runs but it doesn't
numberArray = new Array;
$('.screen_text').html("");
}
numberArray.push(number);
updateDisplay(numberArray);
return numberArray;
}
$('.button_1').click(function(){
numberClick(1, returnValue);
});
$('.button_addition').click(function(){
operationClick("add", concat);
})
$('.button_equals').click(function(){
operationClick("equals", concat, returnValue);
})
預先感謝您的幫助。 非常感謝! 我希望我的代碼不會太亂。
如注釋中所述,返回值不會自動更新任何內容,您需要在調用方中對返回的值執行某些操作。 如果要用新值替換returnValue
全局變量,請分配給它。
$('.button_addition').click(function(){
returnValue = operationClick("add", concat);
});
在operationClick()
函數本身中不會發生這種情況,因為它已經聲明了一個名為returnValue
的局部變量(函數參數自動成為局部變量),並且這遮蓋了全局變量。 您也可以簡單地通過給函數參數一個不同的名稱來解決該問題。
function operationClick(operation, concat, oldReturnValue) {
if (operation == "equals") {
concatComplete = oldReturnValue[1] + concat;
$('.screen_text').html(Number(concatComplete));
}
else if (operation == "add") {
returnValue = [true, concat + "+"];
console.log(returnValue); // The new value is correct here but not anywhere else :(
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.