user3871
user3871

Reputation: 12718

jQuery $.each vs for loop through object

I have the following code to return a Chinese word's English translation on hover.

//return Chinese/English words from database
$("#npc_dialog span").on("mouseover", function() {
    var word = $(this).text();
    $("#currentWord").text(parseHoveredText(word));
}).on("mouseout", function() {
    $("#currentWord").empty();
});

It works with a for loop:

function parseHoveredText (word) {
    for (vocab in hoveredWords) {
        if(word.toLowerCase() === vocab) {
            return hoveredWords[vocab];
        }
    }
};

But does not if I use jQuery $.each.

function parseHoveredText (word) {
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            return value;
        }
    });
};

In both cases, the console.log() of the returned value yields the same value. Why doesn't the jQuery work?

In the for loop:

console.log(hoveredWords[vocab]); gives: You

In the jQuery $.each:

console.log(value); gives: You

Upvotes: 0

Views: 92

Answers (2)

Adil
Adil

Reputation: 148110

The return statement in each will end the each loop instead of returning value from function. You need to return false to finish the for loop instead of returning the value. You should assign value to some variable (that is accessible out the each block) in each loop before returning from each function and return that value from function parseHoveredText

function parseHoveredText (word) {
    var result = "";
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            result = value;
            return false;
        }
    });
    return result;
};

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

it is because you have a anonymous function, when you return the value it is from the each callback function not from the parseHoveredText method.

function parseHoveredText (word) {
    var val;
    $.each(hoveredWords, function(key, value) {
        if(word.toLowerCase() === key) {
            val =value;
            //return false to prevent any further iterations
            return false;
        }
    });
    return val;
};

but from the looks of it, it should be as simple as

function parseHoveredText (word) {
    return hoveredWords[word.toLowerCase()];
};

Upvotes: 3

Related Questions