1

I'm trying to configure a web application that can use client-side JavaScript for localization (as it has to be able to run offline). I've set up a function and a JSON array in my JavaScript like so:

var l10n = {
    "getMessage": function(msg) {
        return locales.en.msg;
    }
}

and

var locales = {
    "en": {
        "applicationName": "This is the application name!",
        "msg": "Looks like we've gotta problem."
    }
}

But if, for example, I enter the command l10n.getMessage("applicationName") the script always returns the "msg" string ("Looks like we've gotta problem." which I've put there for debugging).

The problem is obviously with my l10n.getMessage() function. For all I know, it could be a really simple solution, but with my basic JavaScript knowledge, I can't work out how to fix it. How would I best go about fixing this so that it returns the message for the desired string?

Thanks in advance for your help!

1 Answer 1

2

Yeah, it's actually a simple syntax fix. Use bracket notation to retrieve a property off an object using a variable:

var l10n = {
    "getMessage": function(msg) {
        return locales.en[msg];
    }
};

Demo: http://jsfiddle.net/wC4PN/

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

2 Comments

should we use double quotes for getMessage
@gowri They’re not necessary.

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.