我想知道是否有人可以解释为什么这个函数返回undefined
而不是建立的对象
var people = [
{name: 'John'},
{name: 'Dean'},
{name: 'Jim'}
];
function test(name) {
people.forEach(function(person){
if (person.name === 'John') {
return person;
}
});
}
var john = test('John');
console.log(john);
// returning 'undefined'
返回到forEach
循环将不起作用,您使用的是forEach
回调函数,而不是test()函数。因此,您需要从 forEach
循环外部返回值。
var people = [{
name: 'John'
}, {
name: 'Dean'
}, {
name: 'Jim'
}];
function test(name) {
var res;
people.forEach(function(person) {
if (person.name === 'John') {
res = person;
}
});
return res;
}
var john = test('John');
console.log(john);
或者要从数组中查找单个元素,请使用find()
var people = [{
name: 'John'
}, {
name: 'Dean'
}, {
name: 'Jim'
}];
function test(name) {
return people.find(function(person) {
return person.name === 'John';
});
}
var john = test('John');
console.log(john);
你有两种可能性
具有Array#filter()
的结果集:
// return the result set
function test(name) {
return people.filter(function(person){
return person.name === 'John';
});
}
或布尔值,如果给定名称在数组中,Array#some()
:
// returns true or false
function test(name) {
return people.some(function(person){
return person.name === 'John';
});
}