2013-12-21 290 views
0

我試圖將一個函數的變量傳遞給另一個函數。我認爲這會工作,但我得不到定義。將變量從一個函數傳遞到另一個函數

function launch(){ 
    amount(); 
    finalize(theAmount); 
} 

function amount(){ 
    var theAmount = prompt('How much?'); 
    return theAmount; 
} 

function finalize(theAmount){ 
    alert(theAmount); 
} 

launch(); 
+0

「含量都」是在棧上BRO丟失。你可以在函數之外聲明它(不是最佳實踐,但可以工作)。 – unekwu

回答

4

您正試圖訪問在其他函數中定義的變量。這是不可能的,因爲Javascript's scope restrictions。您必須按原樣傳遞返回值,或者必須將其分配給一個變量,然後將其傳遞給該函數。

無論是在午餐這個功能

function launch(){ 
    finalize(amount()); 
} 

或者

function launch(){ 
    var theAmount = amount(); 
    finalize(theAmount); 
} 
0

您調用量函數,它是返回一個值,但你有沒有收到它。

試試這個修改午餐功能

function launch(){ 
    var theAmount = amount(); 
    finalize(theAmount); 
} 

function amount(){ 
    var theAmount = prompt('How much?'); 
    return theAmount; 
} 

function finalize(theAmount){ 
    alert(theAmount); 
} 

launch(); 
相關問題