我的$.getJSON
功能出现问题,首先我将所有朋友都存储在这样的数组中:
var friends = [];
friends.push({
user: {
username: value.username,
uuid: value.uuid,
accepted: value.accepted,
sent: value.sent
}
});
这是来自$.getJSON
函数的数据并且工作正常。
然后我有一个搜索功能,我在这里搜索我的数据库中的用户名:
$(document).on('keyup', '.search', function() {
$.getJSON('url?username='+$(this).val(), function(data){
$.each(data, function(index, value){
friends.filter(function (friend) {
if(friend.user.username == value.username){
//Append custom
} else {
//append data from JSON
}
});
});
});
});
如果friends数组有一个对象,这可以正常工作。但如果它是空的,没有任何事情发生,它不会附加任何东西。
这里有什么问题?任何帮助表示赞赏
答案 0 :(得分:2)
您应该使用filter
通过评估您的案例是否为true
来返回数组中的匹配项。
var matches = friends.filter(function (friend) {
return friend.user.username == value.username
});
if (matches.length > 0) {
//you had a match in the friends array
console.log(matches[0]);
} else {
//you didn't have a match in the friends array
}