Javascript过滤器数组
为什么以下函数在执行时返回undefined? 似乎filter函数确实返回了适当的对象,所以我不明白为什么它不能传递给回调函数。我对JS很陌生Javascript过滤器数组,javascript,arrays,Javascript,Arrays,为什么以下函数在执行时返回undefined? 似乎filter函数确实返回了适当的对象,所以我不明白为什么它不能传递给回调函数。我对JS很陌生 function getUserById(usersArr, userId, cb){ cb((usersArr.filter(function(el){ return el.id === userId; })[0])); } getUserById(users, '15a', function(user){ return 'Th
function getUserById(usersArr, userId, cb){
cb((usersArr.filter(function(el){
return el.id === userId;
})[0]));
}
getUserById(users, '15a', function(user){
return 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
});
var users = [
{
id: '43d',
email: 'james@gmail.com',
name: 'james',
address: '16 N'
},
{
id: '15a',
email: 'carry@gmail.com',
name: 'Carry',
address: '14 N'
},
{
id: '87t',
email: 'jeff@gmail.com',
name: 'Jeff',
address: '23 N'
},
];
如果您有一个对象数组,并且其中一个或多个对象的ID属性已分配给“15a”,则您的过滤器应该可以工作 下面是一个例子:
function getUserById(usersArr, userId, cb) {
cb(usersArr.filter(function (el) {
return el.id === userId;
})[0]);
}
var users = [{
id: '15a',
name: 'bob',
email: 'bob@example.com',
address: '123 main street'
}, {
id: 'zxv',
name: 'jim',
email: 'jim@example.com',
address: '234 main ave'
}];
getUserById(users, '15a', function (user) {
document.getElementById('output').innerHTML = 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
});
jsfiddle:
编辑:要使示例正常工作,需要返回回调的值
function getUserById(usersArr, userId, cb){
return cb((usersArr.filter(function(el){
return el.id === userId;
})[0]));
}
getUserById(users, '15a', function(user){
return 'The user with the id 15a has the email of ' + user.email + ' the name of ' + user.name + ' and the address of ' + user.address;
});
var users = [
{
id: '43d',
email: 'james@gmail.com',
name: 'james',
address: '16 N'
},
{
id: '15a',
email: 'carry@gmail.com',
name: 'Carry',
address: '14 N'
},
{
id: '87t',
email: 'jeff@gmail.com',
name: 'Jeff',
address: '23 N'
},
];
不要让我们假设。如果您试图返回尚未执行的回调的值,请注意。它将是未定义的。我建议编写一个输出方法,回调调用该方法来分配或输出数据。谢谢。我在repl.it中运行了它,现在也看到了问题所在。JSFIDLE是伟大的。这个答案并没有回答为什么下面的函数在执行时返回未定义的问题?谢谢,我详细阐述了我的答案。