[英]Why does changing the value of function return will change the result of function console.log?
如果我輸入代碼return amount
和console.log(amount)
,它將是1250,但如果我把return balance
和console.log(amount)
,它將是9250! 為什么它如此不同,我不明白。 你能解釋一下嗎?
//Declare variable;
var balance = 10500; // a global variable
var amount = steal(balance, 1250); // a global variable
//Function;
function steal(balance, amount) {
if (amount < balance) {
balance = balance - amount;
}
return amount;
}
console.log(amount); // it will be 1250, cause parameter amount = 1250
如果它將是return balance
,則console.log(amount)
= 9250
您的日志語句記錄在頂部聲明的變量:
var amount = steal(balance, 1250);
由於您將其設置為steal
的返回值,因此根據返回值更改內容並不會讓您感到驚訝。
函數創建一個新的變量范圍,並且參數存在於此范圍內。 參數amount
不會更改外部范圍中的變量amount
:
function steal(balance, amount) {
// amount is a new variable unrelated to the amount from above
}
如果不是這樣,那可能很難調試錯誤。
當你返還金額時,偷取功能的價值坐在金額變量上,這等於1250,當你返還余額時,余額值(余額 - 金額= 9250)坐在金額變量上
var amount = steal(balance, 1250); // if return amount result will be 1250
var amount = steal(balance, 1250); // if return balance result will be 9250
竊取功能的回報坐在金額變量!!! 這很容易!!!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.