2017-04-12 72 views
1
function formatToStandardizedDate(from, to){ 

    const from_date = moment(from); 

    if(to){ 
     let to_date = moment(to); 
    }else{ 
     let to_date = null; 
    } 
} 

console.log(formatToStandardizedDate("2017-04-19 00:00:00",null)) 

我的代碼出現了什麼問題?如果to爲空,它至少會將空值分配給to_date,但我得到了未定義錯誤的to_date錯誤。爲什麼?讓變量沒有定義

+2

讓你不能使用同名的var。 – Jai

+1

[使用「let」和「var」聲明變量有什麼區別?](http://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and- var-to-declare-a-variable) – mxr7350

+0

如果你想在塊外使用它,你需要在塊外定義'let'。 –

回答

6

您不能對let關鍵字使用相同的變量名稱。如果你嘗試這樣做,它會拋出錯誤。


相反,你必須使用三元運算符:

let to_date = to ? moment(to) : null; 

或以上的功能,一次申報,並更新變量

function formatToStandardizedDate(from, to){ 
    const from_date = moment(from); 
    let to_date = null; // initialize the variable with null 
    if(to) 
     to_date = moment(to); // <---here update the variable with new value. 
} 

更新按照JaredSmith的評論和看起來不錯。

+0

但是,它可能是一個'const'。 –

+0

但我想常量不能更新爲新的值。 – Jai

+2

請注意,else子句是完全不必要的,您可以只初始化let let_date = null;並且只在第二個參數是truthy if(to)to_date = moment(to);時才更改它。無論如何,我仍然更喜歡你的三元例子。 –