Js Password Array
My Homework "Create a basic web page that will update Assignment 3.4. Create an array t开发者_如何学Pythonhat will store at least eight valid passwords. Then, ask the user for a password using a prompt dialog. Utilize a for-loop to navigate the password array. If the user's input matches any string in the array, give them feedback that the password is valid. Otherwise, let them know that it is invalid.
You do not necessarily have to include any feature that give them a chance to re-enter the password. This can simply be a one-time search of the password array."
This is for my javascript class... so far I have this:
var accepted_passwords = new Array ( );
accepted_passwords[0] = "Saginaw";
accepted_passwords[1] = "Bay City";
accepted_passwords[2] = "Midland";
accepted_passwords[3] = "Reese";
accepted_passwords[4] = "Millington";
accepted_passwords[5] = "Frankenmuth";
accepted_passwords[6] = "Sheilds";
accepted_passwords[7] = "Birch Run";
var random_bg = new Array ( );
random_bg[0] = "#0000CC";
random_bg[1] = "#33FF33";
random_bg[2] = "#990000";
random_bg[3] = "#9900FF";
random_bg[4] = "#CC0000";
random_bg[5] = "#FF00CC";
var enterpassword;
enterpassword = prompt("Enter Password", "");
for(0 <= i <= 7; enterpassword = accepted_passwords[i];) {
document.body.style.background=random_bg[Math.floor(Math.random()*random_bg.length)];
}
Its supposed to ask for a password... and then if you get it right... it displays one of the five random colors. The random color part works... its the password part that doesn't. I can do this no problem with an if else statement... but apparently my teacher wants a for loop?????? Please help!I think the answer here is that you've fulfilled the teacher's requirement to use a for loop. However there is nothing stopping you also use one or more if..else
constructs too. In fact, if you think about it a bit more, you'll realise there is no way to "check if its a valid password" without an if..else
.
A few observations on how to complete your homework:
Your
for(...)
loop is wrong. for loops always follow the pattern:for([loop-variable-initialisation];[loop-termination-condition];[loop-variable-increment]
eg, for(var i=0;i<10;i++)
// loops for values from 0 to 9
Instead of hard-coding the length of the array, for use in the loop termination condition, it is better to read the
.length
of the arrayYou are currently not checking the value entered exists in the array at all. Worse, your actually (trying to) assign each value in the array to the variable holding the user's input:
enterpassword = accepted_passwords[i]
. This is wrong.
Don't take the statement so literally. He probably means: Use a loop and other required features.
On a side note I would rather use a if(x in y) construct, like described here
EDIT: Removed actual solution.
精彩评论