Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Page 1 of 2 12 LastLast
Results 1 to 15 of 18
  1. #1
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    8
    Thanked 0 Times in 0 Posts

    dereferencing and creating a variable

    So this one is a strange request.
    I have a bunch of vars coming from php that are written into javascript.

    Code:
    var vTest_1 = 'data';
    var vTest_2 = 'data';
    var vTest_3 = 'data';
    .....
    I will know how many vTest_<x> there will be from a var being passes back.

    I have been trying to build vars on the fly. So some of the things I have been trying are:

    Code:
    for (var i = 1; i < myLength; i++) {
    testVV = 'vTest_' ;
    var n = testVV.concat(i); 
        alert(n);
    }
    ok, so n now is vTest_1, vTest_2, ....
    is there a way to get the data from this?

    thanks for any help

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Ummm...can I suggest an alternative?

    Instead of
    Code:
    var vTest_1 = 'data';
    var vTest_2 = 'data';
    var vTest_3 = 'data';
    do this:
    Code:
    var vTest = [];
    vTest[1] = 'data';
    vTest[2] = 'data';
    vTest[3] = 'data';
    And now you simply do
    Code:
    for (var i = 1; i < vTest.length; i++) {
        var value = vTest[i];
        ...
    }
    As an even more efficient alternative, just do this:
    Code:
    var vTest = [
       'data'
       ,'data'
       ,'data'
    ];
    
    for (var i = 0; i < vTest.length; i++) {
        var value = vTest[i];
        ...
    }
    If you are generating that data from a loop in PHP, that's easy. Let's say you are getting the data from a mysql query, for example:
    Code:
    <?php
    echo "var vTest = [\n";
    $delim = "";
    while ( $row = mysql_fetch_assoc($result) ) 
    {
        $data = $row["someField"];
        echo $delim . "'$data'\n";
        $delim = ",";
    }
    echo "];\n";
    ?>
    If the $data values might contain apostrophes, you will need to convert them to \'

    I don't use PHP, but I believe there's a standard function call in PHP to do that. If not, a simple replace will do it.

    NOTE: If you do it as above, the JS array will have elements starting at number zero. If that bothers you, put in a dummy first value so the USABLE elements will start with one.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • Users who have thanked Old Pedant for this post:

    gregd101 (06-21-2012)

  • #3
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,292
    Thanks
    10
    Thanked 583 Times in 564 Posts
    just use json_encode in php to turn the result or php array into a valid, quoted and javascript-native json dump.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #4
    New Coder
    Join Date
    May 2012
    Posts
    20
    Thanks
    8
    Thanked 0 Times in 0 Posts
    thank you Old Pedant.
    I can't believe I didn't see that before.

  • #5
    Regular Coder
    Join Date
    Aug 2010
    Posts
    966
    Thanks
    19
    Thanked 211 Times in 209 Posts
    Quote Originally Posted by gregd101 View Post
    So this one is a strange request.
    I have a bunch of vars coming from php that are written into javascript.

    Code:
    var vTest_1 = 'data';
    var vTest_2 = 'data';
    var vTest_3 = 'data';
    .....
    I will know how many vTest_<x> there will be from a var being passes back.

    I have been trying to build vars on the fly. So some of the things I have been trying are:

    Code:
    for (var i = 1; i < myLength; i++) {
    testVV = 'vTest_' ;
    var n = testVV.concat(i); 
        alert(n);
    }
    ok, so n now is vTest_1, vTest_2, ....
    is there a way to get the data from this?

    thanks for any help
    if the vars are global...
    Code:
    <!doctype html>
    <head>
    <title>phpvars</title>
    
    </head>
    <body><div>
    
    <script>
    myLength = 3;
    var vTest_1 = 'data1';
    var vTest_2 = 'data2';
    var vTest_3 = 'data3';
    for (var i = 1; i < myLength+1; i++) {
    testVV = 'vTest_' ;
    var n = testVV.concat(i); 
        alert(n +" = "+window[n]);
    }
    </script>
    </body>
    </html>

  • #6
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Or you can use eval(). But either one is a hack compared to using an array.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #7
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,609
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by DaveyErwin View Post
    if the vars are global...
    You shouldn't be using global vars at all in JavaScript except for providing access between your code and a framework that it uses.

    For example if your script uses Jquery you'd wrap it like this so that only the jquery variable itself needs to be global:

    Code:
    (function($) {
    // your code goes here
    })(jquery);
    Also in properly written JavaScript you would have just one var statement at the top of each functions to define the variables the function uses.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #8
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Also in properly written JavaScript you would have just one var statement at the top of each functions to define the variables the function uses.
    Now this is one that I disagree with.

    I don't understand the importance of that, at all.

    I see no difference whatsoever between
    Code:
    function foo() 
    {
        var messageDiv = document.getElementById("message"); // errors go here
        var resultsField = document.getElementById("theForm").results; // results here
        var pi = 3.14159265;
        var x = 0;
        ...
    And this:
    Code:
    function foo() 
    {
        var 
        messageDiv = document.getElementById("message"), // errors go here
        resultsField = document.getElementById("theForm").results, // results here
        pi = 3.14159265,
        x = 0;
        ...
    Except that the latter sure looks one whole heluva lot LESS clear to me! The first one is CLEARLY stating that each of those names is a variable. The latter could be confused with simple variable assignments, with the whole point that you are declaring a variable obscured.

    I will grant you that this may come from my experience with other languages, where you have to provide a type:
    Code:
    int foo( )
    {
        Div messageDiv = document.getElementById("message"); // errors go here
        TextInput resultsField = document.getElementById("theForm").results; // results here
        double pi = 3.14159265;
        int x = 0;
    But, still, I can't see how omitting the extra vars adds any readability, maintainability, or debuggability to the code.

    Yes, I've read the JavaScript gurus who propose that. I still think they are espousing something that has no real value.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #9
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,292
    Thanks
    10
    Thanked 583 Times in 564 Posts
    you can add vars later if you forget.
    this can keep them out of the way and lets you list them all in one place.

    it's easier to write because you can just code your function using whatever names make sense, without having to decide up-front what those names are. you never know when you need an "x2". it makes it safer/simple to define a var (or two?) inside an if/else statement without worrying about accidental globals.

    Code:
    function foo() 
    {
        messageDiv = document.getElementById("message") // errors go here
        resultsField = document.getElementById("theForm") // results here
        pi = 3.14159265
        x = 0
     return pi;
     var pi, messageDiv, resultsFields, x;
    }
    i know the syntax might surprise anyone who hasn't read the spec, but it's perfectly valid.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #10
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Yeah, I know that's possible. I'd never use it, but that's me. Again, it probably comes from my experience with strongly-typed languages: I really do want to declare all variables both individually and up front. I will admit, though, to doing things like
    Code:
        for ( var i = 0; i < xxx.length; ++i )
    to declare for loop (or while loop) variables. But, again, I can do that in (most) strongly typed languages, as well, so it makes sense for me to do it in JavaScript.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #11
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,292
    Thanks
    10
    Thanked 583 Times in 564 Posts
    using a var after after a for is customary, and it actually tests slightly faster than a top-of-the-function declaration in my experience. it's probably easier for JIT to trace/optimize the loop if the counter is known by the the loop handler...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #12
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    My comment re var in the for initialization was really directed more towards Felgall's assertion that *ALL* variables in a function should be declared at the start of the function. I agree with you. Felgall's way (and others' way, to be fair) just seems like tedium and overkill, to me.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #13
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,609
    Thanks
    0
    Thanked 645 Times in 635 Posts
    Quote Originally Posted by Old Pedant View Post
    Except that the latter sure looks one whole heluva lot LESS clear to me!
    I agree. That's why I never write my code that way.

    I'd code it as:

    Code:
    function foo() 
    {
        "use strict";
        var messageDiv, resultsField, pi, x;
        messageDiv = document.getElementById("message"); // errors go here
        resultsField = document.getElementById("theForm").results; // results here
        pi = Math.PI; // a more accurate value than in your code
        x = 0;
    ...
    Much clearer and provides a complete list of all the variables the function uses at the top - and still passes validation because it only uses one var statement per function.

    You also know that the list of variables in the var statement is complete because if you leave one out then the script will not run. An ideal way of documenting all the variables that the function uses within the code of the function itself.

    Also declaring the vars at the top like that corresponds to the way that JavaScript will treat them anyway as JavaScript hoists all variable declarations to the top of the function so defining them there yourself makes the code more accurately match the way you'd expect it to work in other languages. Just because you don't var pi until after two to other statements doesn't stop the pi variable existing with a value of undefined up until you assign it a different value.
    Last edited by felgall; 06-22-2012 at 11:17 PM.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #14
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    Okay, I can buy that style.

    Do the declaration and initialization completely separately.

    I've seen people do that even in strongly typed languages, having one line per type.

    I still don't see how it's different or better than putting the keyword var in front of each initialization, but it's definitely better looking than the
    Code:
         var
             name = xxxx,
             foo = yyyy,
             e = 2.718281828;
    that others recommend.

    I have no objection to putting all (or most all) variables at the top of the function, because that's how I've always done it in other languages. (The declaration of for and while variables being reasonable exceptions, to me.) I just don't like the ugly syntax just above. Yours is quite readable and (I think) quite maintainable.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.

  • #15
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,133
    Thanks
    75
    Thanked 4,338 Times in 4,304 Posts
    ... and still passes validation ...
    Almost missed that. Validation by what/whom? Surely not "use strict"??

    I put my var declarations on multiple lines, used "use strict", and it passed FF and Chrome just fine.

    Or were you just saying that's one way to pass validation? If so, yes, of course.
    An optimist sees the glass as half full.
    A pessimist sees the glass as half empty.
    A realist drinks it no matter how much there is.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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