I’m new to Javascript and trying to learn some basics.
Can you please check if I had done the following correctly? If not, please outline what I’ve yet to do.
I had to:
- Calculate the user’s month of birth as a number where January=0 through to December=11.
- Take the string entered
- Get the substring being the first three characters
- Convert to uppercase
- Find the starting location of the three letter abbreviation in the month abbreviations string
- Divide this by 3
- (This is not the only way to find the month number, but it allows us to practice searching in a string)
My code:
var year = prompt('Enter year of birth as a 4 digit integer');
var month = prompt('Enter the name of the month of birth');
// Chop everything after the first 3 characters and make it lowercase
month = month.substr(0,3).toLowerCase();
// Store your array in months, differently named than the month input
var months = ["jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct",
"nov", "dec"];
// We then use array.indexOf() to locate it in the array
var pos = months.indexOf(month);
if (pos >= 0) {
// valid month, number is pos
}
Your code obviously does not follow the given instructions:
But does meet the requirement to calculate the user’s month of birth as a number. I think array search is even superior to string search (no harm by finding strings between the month names (
"anf"etc), and also faster because of not checking these possibilities), but they seem to want you to do it with their way.