>我正在尝试在下面的给定数组中搜索用户名。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.prototype.some()
方法。some
方法类似于every
方法,但在函数返回为 true 之前一直有效。欲了解更多信息,请访问:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some
function checkProfile (profiles,userid) {
var message = "Userid not found"
profiles.some(function(user) {
if(user.personalInformation.userName === userid) {
message = user.personalInformation.firstName+" "+user.personalInformation.secondName;
}
})
console.log(message);
};
checkProfile(userProfiles,"KounBanega3245");
那是因为它在forEach
的第一次迭代中运行if
情况,然后在第二次迭代中,它处理数组中的第二项,导致else
子句运行。
更全面的方法是使用过滤器/映射/减少:
userProfiles
// Only keep the one that we want
.filter(function(user) {
return user.personalInformation.userName === userid;
})
// extract the user's name
.map(function(user) {
return user.personalInformation.firstName + " " + user.personalInformation.secondName;
})
// Get the first (and only) item out of the array
.pop();
这不能解决任何错误检查(例如,如果用户不在原始数组中(。