2016-11-11 67 views
-2

爲什麼此函數返回undefined而不是「舊」?爲什麼我的條件操作符不工作?

function test(age) { 
    12 < age ? "old" : "young"; 
} 

test(15); 
+0

因爲這是無效的JavaScript。閱讀http://stackoverflow.com/questions/11069278/javascript-if-else-shorthand – dahrens

+0

其實它是有效的JavaScript –

回答

3

您的狀況良好。您需要return

function test(age) { 
 
    return 12 < age ? "old" : "young"; 
 
} 
 

 
console.log(test(15));

當你離開掀起了return語句,函數返回undefined默認。