2017-05-29 329 views
3

此代碼將輸出記錄爲零。輸出應爲6.爲什麼JavaScript將其記錄爲「0」?

function sum(a,b){ 
 
    r=a+b; 
 
    return r; 
 
} 
 

 
r=sum(2,9); 
 
r1=sum(1,4); 
 
diff=r-r1; 
 

 
console.log(diff);

+0

你在哪裏宣佈r?看起來它可能超出了函數的範圍,所以當你調用sum時它會覆蓋r。因此,你從自身中減去相同的值並得到0. – Christopher

+1

你需要聲明所有的'r'變量,否則當你的第二個'sum'調用'r'被覆蓋爲'r = 5'時, – Lixus

回答

6

你已經在你localy聲明否則溫控功能內r變量使用var關鍵字,你就會有一個範圍衝突r在函數內部將globaly聲明,並認爲是與r相同的變量變量外功能:

function sum(a,b){ 
    var r=a+b; 
    return r; 
} 

希望這有助於。

function sum(a,b){ 
 
    var r=a+b; 
 
    return r; 
 
} 
 

 
r=sum(2,9); 
 
r1=sum(1,4); 
 
diff=r-r1; 
 

 
console.log(diff);

2

r被稱爲內部和的sum外部。它不是局部變量,而是存在於函數之外。對sum的任何呼叫都將覆蓋之前的值r

特別r1=sum(1,4);都將rr1設置爲5,等等diff於是將0

4

您需要聲明變量時使用var。通過不使用var您隱式創建全局變量。

function sum(a,b){ 
    r=a+b; // This ends up being a reference to the same `r` as below 
    return r; 
} 

r=sum(2,9); // This creates a global variable called r and sets it to 11 
r1=sum(1,4); // This sets global `r` to 5 (because of the r=a+b in sum() 
diff=r-r1; // 5 - 5 is 0 
console.log(diff); 

而是做到這一點:

function sum(a,b){ 
    var r=a+b; // Now this r is local to the sum() function 
    return r; 
} 

var r=sum(2,9); // Now this r is local to whatever scope you are in 
var r1=sum(1,4); 
var diff=r-r1; 
console.log(diff); 
0

這是因爲你還沒有宣佈與VAR keyword.So的

函數內部的變量r,它是在全球範圍內。

當你在做這個R1 =總和(1,4)中,r的值被重寫到

5和r1的值也是5.So R-R1的差變爲

爲0.

爲了避免這種情況,可以使用var關鍵字在函數內聲明r。

function sum(a,b){ 
    var r=a+b; 
    return r; 
} 

r=sum(2,9); 
r1=sum(1,4); 
diff=r-r1; 

console.log(diff); 

這將有所幫助。