SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript function similar to php extract()?

    In PHP, I can create variables based on an associative array:
    PHP Code:
    $a["color"] = "red";
    $a["bool"] = "false";
    $a["name"] = "jon";

    /*
    extract gives me:
    $color, $bool, and $name with their respective values
    */
    extract($a); 
    At the moment, the only thing I can think of to do in Javascript is this:
    Code:
    var a = {
      color:"red",
      bool:"false",
      name:"jon"
    };
    for (var i in a) {
     eval("var " + i + " = '" + a[i] + "'");
    }
    I really hate to use eval() - is there another way?

    TIA,

    Jon

  2. #2
    SitePoint Wizard dreamscape's Avatar
    Join Date
    Aug 2005
    Posts
    1,080
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    how about using window? You could even make an extract function.

    This test seems to work fine:
    Code:
    function extract(variable) {
    	for (var key in variable) {
    		window[key] = variable[key];
    	}
    }
    
    var a = {
      color:"red",
      bool:"false",
      name:"jon"
    };
    
    extract(a);
    
    alert(color);
    alert(bool);
    alert(name);

  3. #3
    SitePoint Addict jtrelfa's Avatar
    Join Date
    Oct 2004
    Location
    Troy, Mi
    Posts
    231
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Perfect! Thanks!

    (I had forgotton that you can reference elements of the window object without explicitly using the 'window' keyword)


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •