简体   繁体   English

为什么这个方法返回 undefined 而不是布尔值?

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

I have the following method我有以下方法

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

Why is it returning undefined and not a boolean?为什么它返回 undefined 而不是布尔值?

Logical operators don't coerce or return booleans.逻辑运算符不强制或返回布尔值。

!!input will ensure that input is a truthy value and return a boolean. !!input将确保输入是一个真值并返回一个布尔值。 input.type === "private" will also return a boolean. input.type === "private"也将返回一个布尔值。 Since both sides of the operator evaluate to booleans, you'll get the value you're expecting.由于运算符的两边都计算为布尔值,因此您将获得期望的值。

 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' }));

The forced cast of the evaluation of the existence of input to Boolean is not guaranteed.不能保证将输入存在的评估强制转换为布尔值。 Test for existence explicitly.显式测试是否存在。 This also makes clearer the intent of the evaluation.这也更明确了评估的意图。 Additionally, leverage the interpreter to check for errors of intent by reversing order of comparison operands for the === operator.此外,利用解释器通过反转 === 运算符的比较操作数的顺序来检查意图错误。 Comparing input.type to literal "private", the interpreter won't let the mistake ["private" = input.type] slide but would be fine with [input.type = "private"].将 input.type 与文字“private”进行比较,解释器不会让错误 ["private" = input.type] 滑动,但使用 [input.type = "private"] 会很好。 Finally, there's very little cost for employing parentheses to enhance salience of the delineation of phrases.最后,使用括号来增强短语描述的显着性的成本非常低。

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

There's an issue with your input variable.您的input变量存在问题。 The error just says that input is undefined, meaning you never gave it a value.错误只是说input未定义,这意味着您从未给它赋值。 Javascript won't try to resolve an undefined value as false, but rather will just throw the error. Javascript 不会尝试将未定义的值解析为 false,而只会抛出错误。

If you want to test for undefined first, change it to如果要先测试未定义,请将其更改为

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

This way it will check if it's null first, and if it's valid, will evaluate as true and move on to the next calculation.这样它会首先检查它是否为空,如果它有效,将评估为真并继续进行下一个计算。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM