foreach loop and returning value of undefined

老子叫甜甜 提交于 2019-12-20 02:32:59

问题


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'

回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/35791675/foreach-loop-and-returning-value-of-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!