finding the logic error in a greetUser function
My professor says I have a logic error in the greetUser function of code I was already graded on. The code is based on the example in the text, so I'm stunned as to determining the logic. This was her message to me:
The
greetUser
function is not reading the cookie correctly for the returning visitor. Check this line of code in thereadCookie
function - it has a logic error.
This is the readCookie
function:
function readCookie(name) {
开发者_如何学运维var nameEQ = name + "=";
var x = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = cookies[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
This is the greetUser
function:
function greetUser(){
userName = readCookie("rock_username");
if(userName)
alert("Hello " + userName + ", I missed you.");
else
alert("Hello, I am your pet rock");
}
From my novice eyes it all looks logical to me, the same as it was in the text example. Any suggestions
var x = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = cookies[i];
You are iterating on "ca" (what is that?) instead of "x", and then you are reading from the cookies
array? 3 different variables, same meaning?
I'll explain: var x = document.cookie.split(';');
splits the string stored in document.cookie
into an array, that will effectively be held inside the x
parameter.
Then, inside the for()
construct, you are increasing i
up until the amount of elements found inside the array you just created from splitting the string. That way, each time you do c = x[i]
; (correct version) you will get the next portion of the document.cookie
string that you split with the ';' character.
This allows you to work on all the interesting parts of document.cookie
, which are, by definition, the user agent (browser) cookies. In your example, you are iterating over the cookies to find a specific one - the 'name' cookie - in order to print it as a greet to the user.
Good luck!
精彩评论