开发者

javascript for() loop, split(), and array question

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.


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++) {


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜