0

I have the following variable:

var tags = [{name:'Bold', key:'b'}, { name: 'Italic', key:'i'}]

Then, in order to get the correct tag I am working on I built a function:

function getCurrentTag(tagType) {
    $.each(tags, function() {
        if (tagType==this.name) {
            return this;
        }
    });
}

And in the main scope I call it:

currentTag = getCurrentTag('Bold');

But currentTag is always "undefined".

How can I fix this?

Gidi

2
  • And this is why "use jquery" is not the great panacea it's claimed to be. Javascript works all by itself sometimes. Commented Dec 3, 2010 at 14:39
  • jQuery is a library, not a complete language. Commented Dec 3, 2010 at 14:41

4 Answers 4

6
function getCurrentTag(tagType) {
    for(var i = 0, len = tags.length; i < len; i++) {
        if( tags[i].name === tagType )
            return tags[i];
    }
}

using jQuerys .each() or for..in loops to loop over an array is unecessary (slow). Since $.each() applies a callback function per interation you are returning that value to this anonymous function. You never return from getCurrentTag()

Sign up to request clarification or add additional context in comments.

Comments

1

You never return the result of $.each().

1 Comment

Also, further processing on the output of the $.each function will be required. jAndy's way should suffice
1

Use a native javascript function. No need to use jQuery here.

var tags = [{name:'Bold', key:'b'}, { name: 'Italic', key:'i'}],
    getCurrentTag = function (tags, name) {
        var i = 0;
        for (i = 0; i < tags.length; += 1) {
            if (tags[i].name === name) {
                return tags[i];
            }
        }
        return False;
    }


 getCurrentTag(tags, 'Bold');

Comments

0

Why use an array? It would be so much cleaner with a simple object of name value pairs.

var tags = {'Bold':'b','Italic':'i'};
function getCurrentTag(tagType) {
    return tags[tagType] || null;
}

All of that looping with your way of doing it will be slow:

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.