0

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

alert(duh);

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

4
Contributors
7
Replies
8
Views
5 Years
Discussion Span
Last Post by itisnot_me
0

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

0

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'

0

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

0

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. :(

1

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.

Edited by somedude3488

Votes + Comments
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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.