luk*_*asz 3 javascript foreach return-value 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'
Run Code Online (Sandbox Code Playgroud)
返回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);Run Code Online (Sandbox Code Playgroud)
或者从数组中查找单个元素使用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);Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1103 次 |
| 最近记录: |