Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
478 views
in Technique[技术] by (71.8m points)

javascript - Function with forEach returns undefined even with return statement

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?

Demo: http://jsfiddle.net/cNYwz/1/

var data = [{
    "Key": "1111-1111-1111",
        "Email": "[email protected]"
}, {
    "Key": "2222-2222-2222",
        "Email": "[email protected]"
}];


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);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

You could adapt it like this :

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];
        }
    }
}

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...