简体   繁体   中英

foreach loop and returning value of undefined

I was wondering if anyone could explain me why this function return undefined instead of founded object

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'

Returning into forEach loop won't work, you are on the forEach callback function, not on the test() function. So instead you need to return the value from outside the forEach loop.

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

Or for finding a single element from array use 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); 

You have two possibilities

A result set with Array#filter() :

// return the result set
function test(name) {
    return people.filter(function(person){
        return person.name === 'John';
    });
}

or a boolean value if the given name is in the array with Array#some() :

// returns true or false
function test(name) {
    return people.some(function(person){
        return person.name === 'John';
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM