gpt4 book ai didi

javascript - foreach 循环和返回值 undefined

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:43:10 25 4
gpt4 key购买 nike

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

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

关于javascript - foreach 循环和返回值 undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35791675/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com