JS said:
zz = "ty"; ....
zz+="[23]";
ab = eval(zz);
But I would like to use the concatination method, just to learn how it
works.
Concatentaing strings works fine, but it was never a good way to access
values.
I was told that it should be possible to convert an array into a
string that still holds the elements:
That, in itself, sounds ... misunderstood. Who told you that? If
you have a link, I'd like to read it myself
You are not turning a variable into a string, you merely make a string
containing a variable name. Might as well let the variable point to
the value instead of the name.
var ty = [99, 100];
zz = "ty";
Then through zz, it should be possible to add elements to ty:
zz+="[23]";
Appending the string "[23]" does not add any elements to anyting, but
it does add characters to the string. If what you really want is
to add the value "23" to the array currently referenced by the variable
"ty", then the quickest way is:
ty.push(23)
or, for older browsers without a "push" method;
ty[ty.length] = 23;
that can be viewed through "ab":
ab = eval(zz);
document.write(ab.length);
Here it seems you are assuming that evaluating the string will both
1) append 23 to the array
2) evaluate to a reference to that array.
It does neither.
The string you end up with is "ty[23]", there is nothing magic about string
concatenation, so you get exactly what you ask for
When evaluated, using "eval", it does exactly what the expression
ty[23]
would do: look up the value at index 23 of the array referenced by "ty".
Since there is no such element, the resulting value is "undefined". There
is no assignment in that expression, so no change to any array.
I know it seems silly, but I would just like to know what I am doing wrong,
because this method should work.
No, it shouldn't.
Whatever you do using "eval" can also be done without it, and 99.9% of
the time the alternative is shorter, safer, and less likely to blow up
in your face.
I could write something that would append a value to an array, using
eval, but it has so many shortcommings that I fear writing it out,
because someone might use it.
/L 'ab=eval("["+ty+",23]");//DON'T EVER DO THIS!'