繁体   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