为了账号安全,请及时绑定邮箱和手机立即绑定

为什么在我的 jQuery 循环中返回不起作用?

为什么在我的 jQuery 循环中返回不起作用?

一只萌萌小番薯 2021-11-18 21:01:43
我有以下函数,在该函数中,将在对象数组中查找 ID,查找匹配的对象,并返回其名称。function find_object(id) {    $.each(array_of_objects, function(index, obj) {        if (obj.id === id) {            console.log('returning');            console.log(obj.name);            return obj.name;        }    });}非常令人困惑的是,它总是会记录正确的obj.name,但返回的值总是undefined。最终我意识到该return语句似乎实际上并未返回,因此我将函数重写为如下所示:function find_object(id) {    var obj_name;    $.each(array_of_objects, function(index, obj) {        if (source.uuid === uuid) {            obj_name = obj.name;        }    });    return obj_name;}这现在可以正常工作。这是怎么回事?
查看完整描述

1 回答

?
慕村9548890

TA贡献1884条经验 获得超4个赞

return在您的第一个示例中,只有returns 来自您传递给forEach.


但返回的值总是未定义的。


那是因为你的find_object函数永远不会返回任何特定的东西。没有显式返回的函数的标准返回值undefined在 Javascript 中。


另外,你为什么不使用Array.prototype.find()?使用方法很简单


function find_object(id) {

    return array_of_objects.find(obj => obj.id === id);

}

或者,如果您只想要name:


function find_object(id) {

    return { name } = array_of_objects.find(obj => obj.id === id);

}

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find


查看完整回答
反对 回复 2021-11-18
  • 1 回答
  • 0 关注
  • 140 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信