foreach 循环和返回值 undefined
foreach loop and returning value of undefined
我想知道是否有人可以解释为什么这个函数返回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';
});
}
相关文章:
- Javascript返回值只在循环中返回一次
- XMLHttpRequest未返回值-状态202
- 根据是否解析了 Promise 从函数返回值
- Angular,函数在(模型)工厂中返回值
- AngularJS错误:提供程序必须从$get工厂方法返回值
- 如何从客户端的数组中获取用户输入和返回值
- Javascript中带有返回值的嵌套函数
- 为变量分配多个nodejs导出返回值时出现问题
- 通过回调从onreadystatechange返回值
- 从Ajax函数返回值
- JavaScript生成器中收益率返回值的解析
- HTML如何根据javascript函数的返回值限制文本输入
- 返回值+new Date()与Date.now()是否不同
- 使用在函数外部声明的变量的 Javascript 返回值 + undefined
- 节点函数在请求完成之前返回“undefined”,并具有所需的返回值
- foreach 循环和返回值 undefined
- 为什么在对象返回值时会返回undefined
- 为什么“typeof false || undefined”返回"布尔值”;
- JQuery: ajax请求返回值"undefined"在同一个函数内
- 如果函数以null或undefined调用,则显示错误,否则返回值