...

View Full Version : dereferencing and creating a variable



gregd101
06-21-2012, 08:41 PM
So this one is a strange request.
I have a bunch of vars coming from php that are written into javascript.



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:




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

Old Pedant
06-21-2012, 09:02 PM
Ummm...can I suggest an alternative?

Instead of

var vTest_1 = 'data';
var vTest_2 = 'data';
var vTest_3 = 'data';

do this:


var vTest = [];
vTest[1] = 'data';
vTest[2] = 'data';
vTest[3] = 'data';

And now you simply do


for (var i = 1; i < vTest.length; i++) {
var value = vTest[i];
...
}

As an even more efficient alternative, just do this:


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:


<?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.

rnd me
06-21-2012, 09:09 PM
just use json_encode in php to turn the result or php array into a valid, quoted and javascript-native json dump.

gregd101
06-21-2012, 09:13 PM
thank you Old Pedant.
I can't believe I didn't see that before.

DaveyErwin
06-21-2012, 09:19 PM
So this one is a strange request.
I have a bunch of vars coming from php that are written into javascript.



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:




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

<!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>

Old Pedant
06-21-2012, 09:24 PM
Or you can use eval(). But either one is a hack compared to using an array.

felgall
06-21-2012, 11:33 PM
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:


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

Old Pedant
06-22-2012, 02:41 AM
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

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:


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:


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.

rnd me
06-22-2012, 06:19 AM
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.


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.

Old Pedant
06-22-2012, 07:37 PM
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

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.

rnd me
06-22-2012, 10:33 PM
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...

Old Pedant
06-22-2012, 11:01 PM
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.

felgall
06-22-2012, 11:12 PM
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:


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.

Old Pedant
06-23-2012, 01:54 AM
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

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.

Old Pedant
06-23-2012, 02:04 AM
... 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.

felgall
06-23-2012, 02:20 AM
Almost missed that. Validation by what/whom?

The JavaScript validator - at http://jslint.com (which both validates your code according to the standards and also warns you if you use valid code that is known to cause problems). Created by one of those involved in the actual JavaScript specification itself and person who originally created the JSON object that is now a part of JavaScript. The validator is a bit stricter than "use strict" since it also warns about those constructs that they decided were too difficult to remove from the current version of JavaScript but which they hope to do something about in the next version.

The one benefit that my way of declaring the variables has is that the declarations are at the same point in the code as where JavaScript actually creates them. When you scatter the var statements through the function they still all get declared first before the first assignment statement is run. For those used to languages where variables can have block scope declaring them all at the top of the function in JavaScript makes the script easier to understand since those used to block scope might otherwise think that variables declared inside a block only exist within the block. With a for statement declaring i inside the for statement doesn't mean it only exists within the for statement - it is still created at the start of the function and continues to exist until the function (and not the for loop) finishes - which is different from languages with block scope where declaring the variables at their first actual use makes more sense.

venegal
06-23-2012, 03:03 AM
The JavaScript validator - at http://jslint.com (which both validates your code according to the standards and also warns you if you use valid code that is known to cause problems). Created by one of those involved in the actual JavaScript specification itself and person who originally created the JSON object that is now a part of JavaScript. The validator is a bit stricter than "use strict" since it also warns about those constructs that they decided were too difficult to remove from the current version of JavaScript but which they hope to do something about in the next version.

In some other document, Crockford actually recommends Old Pedant's style:


It is preferred that each variable be given its own line and comment. They should be listed in alphabetical order.

var currentEntry; // currently selected table entry
var level; // indentation level
var size; // size of table

But he admits to adding to JSLint whenever he gets burned by a particular practice, so that's that. One way or another, there's definitely merit in not scattering var declarations throughout the function (and if limiting oneself to a single var in order to achieve that consistently, why not do it that way).

@Old Pedant: This example might be a bit contrived, but I suppose this simple mistake is the reason why it's recommended not to declare variables inside a for statement:


var i = 'outer';
function alertOuter() {
alert(i); // undefined
for (var i = 0; i < 1; i++) {}
}

Anyway, personally I prefer a bit of a mix between your two styles, namely using several var declarations to group variables semantically. I don't particularly like the alphabetical approach, and find that this grouping approach makes for decent maintainability:


// DOM stuff
var $container, $content, $buttons;

// Dimensions
var containerWidth, containerHeight;

// Counters
var i, j, k;


And, btw, my reason for not doing the same with a single var declaration is that I don't like the idea of having to mess with the semicolon in the last line whenever I'm adding to the list (and probably aesthetic preferences).

Old Pedant
06-23-2012, 03:33 AM
Yes, I do and did know that JS doesn't support block scope (unfortunately) and is one reason I'm very careful to use different loop variables. I don't use many global variables (not as fanatic as Felgall about that, but I agree with him in principle), so your contrived example isn't one I've ever run into. (Truly never...possibly partly luck, but partly just taking care.)

Didn't realize Felgall was referring to Doug Crockford. Met him oh so many years ago when he was working for Atari (when we did contract work for Atari). I have of course seen his name crop up from time to time (a lot), but didn't realize he was the one behind jsLint. Anyway, I'm still a pragmatist. If it works, don't fix it, is usually my motto. But when I start to build something else from scratch, I try to use what I have learned. So Felgall has pushed me into modifying some of my code. All to the good.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum