views:

365

answers:

2

Ok I've been asking alot of JS questions lately, and realized I just need to go learn it.

Been following tutorials at http://www.tizag.com/javascriptT very simple and straightforward.

I just want to make sure I understand this correctly. It took me a while to get it:

<script type="text/javascript">
var myString = "zero one two three four";

var mySplitResult = myString.split(" ");

for(i = 0; i < mySplitResult.length; i++){
    document.write("<br /> Element " + i + " = " + mySplitResult[i]); 
}
</script>

-

var myString = "zero one two three four";

Obviously that creates a simple string variable.

var mySplitResult = myString.split(" ");

That splits it using " " as the delimeter, and assigns it to the mySplitResult array. Correct? Or is it not an array?

for(i = 0; i < mySplitResult.length; i++){

Is this saying the number of values in the array? Doesn't seem like it could be saying the actual length of characters in the string.

document.write("<br /> Element " + i + " = " + mySplitResult[i]);

This just returns mySplitResult[i] variable "i". Since i is increasing with each loop, it pulls the correct information from the array.

+1  A: 

Your analysis is correct, but you should see that by just testing it. Use Firebug extension with Firefox and you can step through your javascript.

This will help you understand what is going on, as you can then look at properties of the element and monitor what is actually happening.

James Black
+1  A: 

Your understanding is essentially correct. One thing you should do is declare all your variables: this is particularly important inside functions. So, you should declare i as a variable, either before the loop:

var i;
for (i = 0; i < mySplitResult.length; i++) {

... or in the first expression in the for statement:

for (var i = 0; i < mySplitResult.length; i++) {
Tim Down