2016-06-12 65 views
-4

有什麼區別我用這些比較的人照顧或者是他們完全地一致:不同的方法來返回true或false

return !!(foo == 'bar') 

return (foo == 'bar') ? true : false; 

if (foo == 'bar') return true; 
else return false; 
+4

你錯過了最好的選擇:'return foo ==='bar'' – elclanrs

+0

另外:'return foo ==「bar」&& true || false','返回Boolean(foo ==「bar」);','return [false,true] [Number(foo ==「bar」)]];或者其他你可能想要做的事情。 – Bergi

+0

可能重複[什麼是!! (not not)operator?](http://stackoverflow.com/q/784929/1529630)和[JavaScript中的問號標記](http://stackoverflow.com/q/1771786/1529630) – Oriol

回答

-1

最好的一個(不包括在名單)是

return foo === 'bar'; 

所有表達式返回相同的結果,但由於=====運算符返回可以簡化表達,並具有更可讀代碼的布爾值。