为什么此方法返回未定义而不是布尔值?

时间:2019-03-01 17:28:46

标签: javascript node.js methods boolean undefined

我有以下方法

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

console.log(isPrivate());

为什么它返回未定义而不是布尔值?

3 个答案:

答案 0 :(得分:1)

逻辑运算符不强制或返回布尔值。

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

答案 1 :(得分:0)

不能保证强制转换为布尔值的输入是否存在。明确测试是否存在。这也使评估的意图更加明确。另外,利用解释器通过反转===运算符的比较操作数的顺序来检查意图错误。将input.type与文字“ private”进行比较,解释器不会让错误[“ private” = input.type]滑动,但可以使用[input.type =“ private”]来解决。最后,使用括号来提高短语描述的显着性几乎没有成本。

const isPrivate =(输入)=> {     return(“ undefined”!== typeof input)&&(“ undefined”!== typeof input.type)&&(“ private” === input.type); };

答案 2 :(得分:-1)

您的input变量存在问题。该错误只是表明input是未定义的,这意味着您从未给它赋值。 Javascript不会尝试将未定义的值解析为false,而只会抛出错误。

如果要先测试未定义,请将其更改为

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

这样,它将首先检查它是否为null,如果有效,则将其评估为true,然后进行下一个计算。