我正试图在下面的给定数组中搜索userName。当搜索对象数组中的第二个元素时,Search函数对第二个元素返回true,在搜索第一个元素时返回false作为第一个元素。当我们搜索数组中的现有值时,它应该返回true,但函数返回false为第一个元素,为true返回第二个元素。 我找不到我正在做的错误。即使尝试使用Array.prototype.find()函数,但没有运气。虽然搜索值存在于数组中,但JavaScript函数返回else语句
//JSON User Information
var userProfiles = [
\t {
\t \t "personalInformation" : {
\t \t \t "userName" : "Chandu3245",
\t \t \t "firstName" : "Chandrasekar",
\t \t \t "secondName" : "Mittapalli",
\t \t \t "Gender" : "Male",
\t \t \t "email" : "[email protected]",
\t \t \t "phone" : ["740671xxx8", "8121xxxx74"]
\t \t }
\t },
\t {
\t \t "personalInformation" : {
\t \t \t "userName" : "KounBanega3245",
\t \t \t "firstName" : "KounBanega",
\t \t \t "secondName" : "Karodpati",
\t \t \t "Gender" : "Male",
\t \t \t "email" : "[email protected]",
\t \t \t "phone" : ["965781230", "8576123046"]
\t \t }
\t }
];
function findUserDataWithUserID (userData, userid){
var fullName = "";
//iterates through userData array \t
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',以及它为什么不起作用。 – 2017-08-03 02:22:13
@torazaburo,我编码类似于上面,但代替forEach我写了array.prototype.find()。当我按照以下建议更正时,它工作正常。 – CHandu3245