【发布时间】:2013-04-12 00:31:53
【问题描述】:
我正在使用 Meteor,人们可以通过 Facebook 连接到该网站。我正在使用人员用户名来识别他们。但是,其中一些没有用户名。例如,新用户的用户名为 null。我想做的是,如果这个人有用户名,那么我们使用他们的用户名。如果没有,我想用他们的 Facebook id 作为他们的用户名。问题是,我的 if 条件无法正常工作。如果此人有用户名,则 if 条件认为此人没有。奇怪的是,如果我在 if 条件之前执行用户名的 console.log,它将显示用户名。但是一旦在if中,它认为用户名是空的。这是代码:
Accounts.onCreateUser(function(options, user) {
var fb = user.services.facebook;
var token = user.services.facebook.accessToken;
if (options.profile) {
options.profile.fb_id = fb.id;
options.profile.gender = fb.gender;
options.profile.username = fb.username
console.log( 'username : ' + options.profile.username);
if ( !(options.profile.username === null || options.profile.username ==="null" || options.profile.username === undefined || options.profile.username === "undefined")) {
console.log('noooooooo');
options.profile.username = fb.id;
} else {
console.log('yessssssss');
options.profile.username = fb.username;
}
options.profile.email = fb.email;
options.profile.firstname = fb.first_name;
user.profile = options.profile;
}
sendWelcomeEmail(options.profile.name, options.profile.email);
return user;
});
使用此代码,如果我使用具有用户名的 Facebook 登录。条件将显示 'noooooooo' 但 console.log('username : ' + options.profile.username);将显示我的用户名。为什么这样做? :l
【问题讨论】:
-
if语句中的条件被!否定。为此运行输入和输出:假设用户名是“brad”。那么条件中的options.profile.username将不等于null,或“null”,或未定义,或“未定义”,因此内部条件将返回false。但是,它随后被!否定,因此您的条件将(至少大部分)以与您想要的相反的方式运行。 -
我还建议更改内部条件。在 JavaScript 中检查变量是否存在的一种标准方法是通过
typeof options.profile.username !== "undefined"。我认为这可能符合您的目的。 -
谢谢你!那行得通:)
标签: meteor