【发布时间】:2017-08-03 01:50:48
【问题描述】:
我正在尝试在下面的给定数组中搜索用户名。 Search 函数在对象数组中搜索第二个元素时为第二个元素返回 true,而在搜索第一个元素时为第一个元素返回 false。当我们在 Array 中搜索现有值时,它应该返回 true,但函数对第一个元素返回 false,对第二个元素返回 true。 我找不到我正在做的错误。甚至尝试使用 Array.prototype.find() 函数,但没有运气。
//JSON User Information
var userProfiles = [
{
"personalInformation" : {
"userName" : "Chandu3245",
"firstName" : "Chandrasekar",
"secondName" : "Mittapalli",
"Gender" : "Male",
"email" : "chandxxxxx@gmail.com",
"phone" : ["740671xxx8", "8121xxxx74"]
}
},
{
"personalInformation" : {
"userName" : "KounBanega3245",
"firstName" : "KounBanega",
"secondName" : "Karodpati",
"Gender" : "Male",
"email" : "KounBanega3245@gmail.com",
"phone" : ["965781230", "8576123046"]
}
}
];
function findUserDataWithUserID (userData, userid){
var fullName = "";
//iterates through userData array
userData.forEach(function(user){
//checks for matching userid
if(user.personalInformation.userName === userid){
fullName=user.personalInformation.firstName+" "+user.personalInformation.secondName;
}else{
fullName = "Userid Not Found";
}
});
return fullName;
}
console.log(findUserDataWithUserID(userProfiles, "Chandu3245"));
【问题讨论】:
-
向我们展示您对
Array#find的尝试,以及为什么它没有成功。 -
@torazaburo,我的编码与上面类似,但我写了 array.prototype.find() 来代替 forEach。当我按照以下建议进行更正时,它工作正常。
标签: javascript