簡體   English   中英

三元運算符在javascript中有返回值嗎?

[英]Does a ternary operator has a return value in javascript?

在 MDN 文檔中,我沒有在語法中找到三元運算符(以及參數描述)的返回值,它指定了一個在 true 時執行的表達式,或者一個在 false 時執行的表達式。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

問題是:三元運算符是否返回值?

Return 語句結束函數執行並提供請求的值。 所以如果你想從函數中返回,你基本上在return的右側使用三元運算符:

function foo() {
 let testValue;
 return testValue ? 'defined' : 'undefined'; // returns 'undefined', because variable was declared, but not initialized by any value, which transformed by engine as false value
}

但是您無法根據某些條件決定是否要返回:

function bar () {
 let testValue;
 testValue ? console.log('defined') : return 'undefined'; // false condition won't work
}

如果您需要根據某些條件決定是繼續計算還是返回某個值,最好使用基本的if語句。


編輯:感謝@deceze,他提到 return 不是一個運算符,而是一個實際的語句。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM