Ok so I am trying to create a loop that creates a dynamic variable but I cant find out how to do this. this is what I have so far

var map = { 
    'flammable': 'inflammable', 
    'duh': 'no duh' 

$.each(map, function(key, value) {  
   var key = value;


But every time I run this is states that duh is not defined. What am I doing wrong?

Recommended Answers

All 7 Replies

it's because you didn't declare a var duh;that's why .. and you should assign a value to it .

Yes i know that but im trying to create a dynamic var. Where var key should create the duh var and the value will be no duh.
ex: var key = value; == var duh = 'no duh'

I believe you can do it like this:

eval("var " + key + " = " + value);

@hearth: That seems to work only with the first entry. Am I creating the array correctly?

the array looks ok to me.

eval("var " + key + " = " + value);

it might be to do with the eval'd code not having a semicolon, but i'm really just guessing at this point.

eval("var " + key + " = " + value + ";");

Maybe its a restriction of jQuery or the for-each loop... sorry, I'm not particularly a jQuery expert. :(

You are running into scope issues. Variables created in a anonymous function are not available outside the function unless they are defined first outside the function (which defeats the purpose of what you are trying to do).

Try this maybe:

for( key in map ) {
    eval('var ' + key + ' = \'' + map[key] + '\'');

Its untested, but should give you an idea. Its best to avoid using eval if possible though.

commented: King +0

@kkeith29: Thanks sooooooo much that is what i was looking for. I am still new to javascript but i can def do php. you would think things would be more side by side.

What im trying to accomplish is sending through a array and break it apart in what i need. Basically im creating my own save/add function for my software.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.