...

View Full Version : Newbie question



javanewbie7
12-21-2010, 08:10 PM
Hello,

I'm in the process of getting a better understanding of javascript (instead of just copying and pasting JQuery script onto my site).

So I have a(dumb?) question. Can I name a var what ever I want? For example,

var car_name("Ford Escape");


Or am I misunderstanding this?

THanks.

DJCMBear
12-21-2010, 08:17 PM
No you can only var letters, numbers and some special chars such as _ (underscore), but to do what you want you can do this. var car_name = ['Ford Escape']; and then you can do this alert(car_name[0]); // alerts Ford Escape

Old Pedant
12-21-2010, 08:17 PM
??? car_name is a fine variable name.

But what's the bit with "Ford Escape"???

That's not legal syntax.

Anyway, no. Variables must consist of only letters, digits, underline, and dollar sign. They can start with any of those characters except a digit.

javanewbie7
12-21-2010, 08:27 PM
OK, I guess this is the example I was thinking of (I got it off of W3Schools) and it's also why I'm confused. SO i use an Array to list the vehicles (or whatever I want to list), correct?


<script type="text/javascript">
var x;
var mycars = new Array();
mycars[0] = "Saab";
mycars[1] = "Volvo";
mycars[2] = "BMW";

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
</script>

Thanks.

DJCMBear
12-21-2010, 08:34 PM
Most codes these days use the object array to store the array data for example like this.



<script type="text/javascript">
var x,
mycars = ["Saab","Volvo","BMW"];
for (x in mycars) {
document.write(mycars[x] + "<br />"); // x equals the current array item number
}
</script>

javanewbie7
12-21-2010, 08:37 PM
Most codes these days use the object array to store the array data for example like this.



<script type="text/javascript">
var x,
mycars = ["Saab","Volvo","BMW"];
for (x in mycars) {
document.write(mycars[x] + "<br />"); // x equals the current array item number
}
</script>

Thanks. That helps.

Old Pedant
12-21-2010, 08:53 PM
Yes, excepting that's a more complicated way to create an array than is necessary.

Try this:


<script type="text/javascript">
var x;
var mycars = ["Saab","Volvo","BMW"];

for (x in mycars)
{
document.write(mycars[x] + "<br />");
}
document.write( "<hr>An easy way to dump the array: " + mycars + "<hr>" );
document.write( "Or another way:<ul><li>" + mycars.join("</li><li>") + "</li></ul>" );
</script>

Old Pedant
12-21-2010, 08:54 PM
Hah. Bear beat me to it. But look at the other ways to dump arrays. Lots of fun to be had by all.

DJCMBear
12-21-2010, 09:20 PM
Hah. Bear beat me to it.

Always funny seeing what you have just posted is the same as someone else's, explaining more or less the same thing.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum