简体   繁体   中英

Javascript: Arrays and For Loop Basics

I'm new to javascript and have been trying to teach myself the basics. I do have some experience with C++.

I came across this example in the source I'm using for studying and the for loop looks strange to me:

<html>
<head>
<script type="text/javascript">
<!--
function ReadCookie()
{
   var allcookies = document.cookie;
   alert("All Cookies : " + allcookies );

   // Get all the cookies pairs in an array
   cookiearray  = allcookies.split(';');

   // Now take key value pair out of this array
   for(var i=0; i<cookiearray.length; i++){
      name = cookiearray[i].split('=')[0];
      value = cookiearray[i].split('=')[1];
      alert("Key is : " + name + " and Value is : " + value);
   }
}
//-->
</script>
</head>
<body>
<form name="myform" action="">
<input type="button" value="Get Cookie" onclick="ReadCookie()"/>
</form>
</body>
</html>

Would someone mind explaining why there is a [0] and [1] near the end of these statements?

name = cookiearray[i].split('=')[0]; value = cookiearray[i].split('=')[1];

A clearer way to write this statement is this:

 var parts = cookiearray[i].split('='),
     name = parts[0],
     value = parts[1];

That doesn't have anything to do with the for-loop itself. Split returns an array of tokens; the string is split up at the given delimiter. You're simply accessing the first and second tokens in this array.

String.split creates an array using the assigned delimiter (in this case '='). The [0] and [1] are selecting the first and second elements of the array respectively (Javascript array element indexes start at zero).

Those are used to access the items in the arrays that you create.

It's more clear what they do, and also better for performance, if you put the array in a variable and access that. That way you don't have to create two identical arrays:

var cookie = cookiearray[i].split('=');
var name = cookie[0];
var value = cookie[1];

该代码将每个cookie对key=value拆分为key( [0] )和value( [1] )。

A for loop is an iterator. You can sort of think of it like a counter, or stepping progression. If you want to do something x number of times, then a for loop is your best friend. The issue, when you are first learning, is figuring out how to use them effectively.

I'll give you a relevant and nonrelevant (simplified) example:

Nonrelevant:

// Increase the value of x and print the new value to the console 20 times.
var x = 6;

for(var i = 0; i < 20; i++) {
    x++;
    console.log("Value of x: " + x);
}

If you take a close look it's really rather logical. You define an iteration variable i , tell it when to stop ( i < 20 ...so stop if i = 20), how to progress with each iteration ( i++ or i + 1).

So the code will enter the loop when i = 0 ...it will add 1 to the value of x (x++), resulting in x = 7. It does the same for each iteration, so when i = 1 , x (7) + 1 = 8, so on and so forth until i = 20, then the code breaks out of the loop and continues on it's merry little way. When it breaks we have just added 1 to x 20 times. Since x used to equal 6, it now equals 26.

Relevant:

// Given array of length 10, print each element to the console

for (var i = 0; i < cookiearray.length; i++){
    console.log(cookiearray[i]);
}

So here the for loop is the same, it simply iterates until i equals the length (number of elements, in this case) of the array (so 10 times). When i = 0 , our code prints the element of the array at cookiearray[0] ...when i = 1 it prints cookiearray[1] ...so on and so forth for the entirety of the array.

What may confuse you in the example is the split function. Split returns an array. So this line:

name = cookiearray[i].split('=')[0];

...actually means assign the first element of the new array created from splitting the cookiearray's element at position i .

Let's assume that cookiearray[0] = "Hello=World" . When i = 0 , our code splits the string "Hello=World" into a new array where the element at the 0 position is "Hello", it then assigns this to the local variable name. So name = "Hello".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM