簡體   English   中英

為什么這個方法返回 undefined 而不是布爾值?

[英]Why is this method returning undefined and not boolean?

我有以下方法

 const isPrivate = (input) => { return input && input.type && input.type === "private"; } console.log(isPrivate());

為什么它返回 undefined 而不是布爾值?

邏輯運算符不強制或返回布爾值。

!!input將確保輸入是一個真值並返回一個布爾值。 input.type === "private"也將返回一個布爾值。 由於運算符的兩邊都計算為布爾值,因此您將獲得期望的值。

 const isPrivate = (input) => { return !!input && input.type === "private"; } console.log(isPrivate()); console.log(isPrivate({})); console.log(isPrivate('')); console.log(isPrivate({ type: 'public' })); console.log(isPrivate({ type: 'private' }));

不能保證將輸入存在的評估強制轉換為布爾值。 顯式測試是否存在。 這也更明確了評估的意圖。 此外,利用解釋器通過反轉 === 運算符的比較操作數的順序來檢查意圖錯誤。 將 input.type 與文字“private”進行比較,解釋器不會讓錯誤 ["private" = input.type] 滑動,但使用 [input.type = "private"] 會很好。 最后,使用括號來增強短語描述的顯着性的成本非常低。

const isPrivate = (input) => { return ("undefined" !== typeof input) && ("undefined" !== typeof input.type) && ("private" === input.type); };

您的input變量存在問題。 錯誤只是說input未定義,這意味着您從未給它賦值。 Javascript 不會嘗試將未定義的值解析為 false,而只會拋出錯誤。

如果要先測試未定義,請將其更改為

return input != null && input && input.type && input.type === "private";

這樣它會首先檢查它是否為空,如果它有效,將評估為真並繼續進行下一個計算。

暫無
暫無

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

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