0

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];

3
  • Is it the loop or the split that is confusing you? If it's the split have a look what the string method does return Commented Dec 17, 2013 at 20:07
  • 1
    The split() is indeed confusing because it is performed twice (for nothing). Commented Dec 17, 2013 at 20:08
  • The second time the split is done (which is in the for loop) is splitting a cookies Key/Value pairing into a usable array. I suppose the data is of the form Key=Value;Key=Value;Key=Value as it would be for cookies...but the .split() function is used on strings so don't get caught up in the key/value discussion...that is not an inherent trait or (most) common use of .split(). Commented Dec 17, 2013 at 20:42

6 Answers 6

3

A clearer way to write this statement is this:

 var parts = cookiearray[i].split('='),
     name = parts[0],
     value = parts[1];
Sign up to request clarification or add additional context in comments.

1 Comment

You might better rename split (which of the two?) into a more descriptive version.
2

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.

Comments

1

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).

Comments

1

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];

Comments

0

The code is splitting each cookie pair key=value into key ([0]) and value ([1]).

1 Comment

key [0] and nothing [1] of what?
0

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".

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.