【问题标题】:The JavaScript function returns else statement though the search value exists in the array尽管搜索值存在于数组中,但 JavaScript 函数返回 else 语句
【发布时间】: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


【解决方案1】:

您也可以为此使用Array.prototype.some() 方法。 some 方法类似于every 方法,但在函数返回为真之前一直有效。欲了解更多信息,请访问: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");

【讨论】:

    【解决方案2】:

    这是因为它在forEach 的第一次迭代中运行if 情况,然后在第二次迭代中,它处理数组中的第二项,导致else 子句运行。

    更全面的方法是使用 filter/map/reduce:

    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();
    

    这并不能解决任何错误检查(例如,如果用户不在原始数组中)。

    【讨论】:

      猜你喜欢
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-08
      相关资源
      最近更新 更多