我在我的appery.io應用程序中使用下面的JavaScript代碼。我不斷收到一個錯誤,指出以下內容:我的JavaScript代碼52行的錯誤,我不知道它
6/25/2014 9:37:35 PM: Script All_Users_Data: TypeError: Cannot read property '_id' of undefined (@ 52 : 33) -> if (all_photo[i].the_user._id == id) {
請幫我指出錯誤。我試圖從3個集合中提取數據,通過_id從'用戶'集合同步它們,然後輸出用戶配置文件類型信息。
var all_users = eval(DatabaseUser.query('52895ecce4b056c5e94f34f9'));
var all_profiles = eval(Collection.query('52895ecce4b056c5e94f34f9', 'profile'));
var all_status = eval(Collection.query('52895ecce4b056c5e94f34f9', 'Status'));
var all_photo = eval(Collection.query('52895ecce4b056c5e94f34f9', 'photo'));
// loop on all users
for (var i=0;i<all_users.length;i++)
{
// call function to search for user profile and then add first name to current user item
getProfile(all_users[i]._id, all_users[i]);
// call function to search for user status and then add last status to current user item
getstatus(all_users[i]._id, all_users[i]);
getphoto(all_users[i]._id, all_users[i]);
}
// function get user item and user id and find user profile by its id and update it
function getProfile(id,curUser)
{
var found = false;
for (var i = 0; i < all_profiles.length; i++) {
// if cur user id = profile id assign profile name to the user
if (all_profiles[i].the_user._id == id)
{
curUser.firstName = all_profiles[i].firstName;
curUser.university = all_profiles[i].university ;
found = true;
}
}
if (!found)
{
curUser.f_name = "";
}
}
// function get user item and user id and find user status by its id and update it
function getstatus(id, curUser) {
var found = false;
for (var i = 0; i < all_status.length; i++) {
if (all_status[i].the_user._id == id) {
curUser.status = all_status[i].status;
found = true;
}
}
if (!found) {
curUser.status = "";
}
}
function getphoto(id, curUser) {
var found = false;
for (var i = 0; i < all_photo.length; i++) {
if (all_photo[i].the_user._id == id) {
curUser.photo = all_photo[i].photo;
found = true;
}
}
if (!found) {
curUser.photo = "";
}
}
// return full user data updated wih status and first name
response.success(JSON.stringify(all_users), "application/json");
看起來像all_profiles中的the_user對象爲null。嘗試在控制檯中驗證結果,方法如下: console.log(all_profiles [i]); – Ash
訪問對象的元素之前,應檢查它們是否已定義。 – Gabs00
'eval()' - 等等,什麼?這很可能是此代碼中的前4個錯誤。 – Bergi