即使使用return语句,forEach函数也会返回undefined [英] Function with forEach returns undefined even with return statement

查看:102
本文介绍了即使使用return语句,forEach函数也会返回undefined的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是创建一个函数来检查对象数组中的某个值,但由于某种原因它会一直返回 undefined 。为什么?

I'm just making a function for checking a value of something in my object array, but for some reason it keeps returning undefined. Why is that?

演示: http:// jsfiddle .net / cNYwz / 1 /

var data = [{
    "Key": "1111-1111-1111",
        "Email": "test@test.com"
}, {
    "Key": "2222-2222-2222",
        "Email": "test@boo.com"
}];


function getByKey(key) {    
    data.forEach(function (i, val) {
        if (data[val].Key === key) {
            return data[val].Key;
        } else {
            return "Couldn't find";
        }
    });
}

var asd = getByKey('1111-1111-1111');
console.log(asd);


推荐答案

在你的函数中,你从函数返回传递给 forEach ,而不是来自 getByKey

In your function, you're returning from the function passed to forEach, not from getByKey.

你可以像这样适应:

function getByKey(key) {    
    var found = null;
    data.forEach(function (val) {
        if (val.Key === key) {
            found = val;
        }
    });
    return found;
}

但这将迭代所有元素,即使立即找到该项目。这就是为什么你最好用来表示循环:

But this would iterate over all elements, even if the item is immediately found. That's why you'd better use a simple for loop :

function getByKey(key) {    
    for (var i=0; i<data.length; i++) {
         if (data[i].Key === key) {
            return data[i];
        }
    }
}

请注意,我也调整了你的代码返回值,而不是键。我想那是意图。您可能还与另一个迭代函数混淆:第一个参数传递给您给 forEach 是数组的元素。

Note that I also adapted your code to return the value, not the key. I suppose that was the intent. You might also have been confused with another iteration function : the first argument passed to the callback you give to forEach is the element of the array.

这篇关于即使使用return语句,forEach函数也会返回undefined的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆