繁体   English   中英

foreach循环和返回undefined的值

[英]foreach loop and returning value of undefined

我想知道是否有人能解释为什么这个函数返回undefined而不是found对象

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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