[英]Conditionally check if a value that may at times be undefined is not equal to another value?
var query = [], name = 'name';
if (body.displayName !== req.user.displayName) {
query.push({
displayName: name
});
}
This works, but I've run into a use-case where req.user.displayName === undefined
. 这
req.user.displayName === undefined
,但是我遇到了一个用例,其中req.user.displayName === undefined
。
Intuitively, it would seem undefined
would also not be equal to body.displayName
, but of course it throws an error: 直观地,似乎
undefined
也不等于body.displayName
,但是当然会引发错误:
"cannot read property of undefined"
“无法读取未定义的属性”
Is there anyway to have this conditionally check if the value is undefined
and also not equal to body.displayName
within the same if statement, or is the only way to nest this within another if statement: 无论如何,是否有条件地检查该值是否在相同的if语句中
undefined
并且也不等于body.displayName
,还是将其嵌套在另一个if语句中的唯一方法:
if (req.user.displayName !== undefined) { }
That error cannot come from req.user.displayName
being undefined
. 该错误不能来自
req.user.displayName
undefined
。 It comes from trying to read a property of something that's undefined, which means that the culprit is that body
, req
or req.user
is undefined
. 它来自尝试读取未定义内容的属性,这意味着罪魁祸首是
body
, req
或req.user
undefined
。
Here's a transcript from node.js: 这是来自node.js的成绩单:
> body = {displayName: "foo"}
{ displayName: 'foo' }
> req = {user: {displayName: undefined}}
{ user: { displayName: undefined } }
> req.user
{ displayName: undefined }
> req.user.displayName
undefined
> body.displayName !== req.user.displayName
true
No problems at all, even though req.user.displayName
is undefined
. 即使
req.user.displayName
是undefined
,也没有任何问题。
You don't need to change your if
test; 您无需更改
if
测试; you need to track down why one of those other objects is undefined
. 您需要跟踪为什么
undefined
其他对象之一的原因。
So figure out what is undefined 所以找出未定义的是什么
console.log(req);
console.log(req.user);
I am assuming the bug is that user is not set. 我假设错误是未设置用户。 If that can be true, than you do not have an issue.
如果那是真的,那您就没有问题了。 If it should have a user than you have a bug.
如果它应该有一个用户,那么您将有一个错误。
But the basic check would use a truthy check to make sure the object s there. 但是基本检查将使用真实检查,以确保对象位于此处。 It could be either one of the following depending what is undefined.
根据未定义内容,它可以是下列之一。
if (req && req.user && req.user.displayName !== body.displayName)
or 要么
if (req.user && req.user.displayName !== body.displayName)
or if body
is undefined
, you would need to do the check the other way. 或者,如果
body
undefined
,则需要用另一种方法进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.