Reputation: 33
I have a problem with this code:
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
var fruits = new Array ("apple", "orange", "banana");
for(i=0; i < fruits.length; i++) {
if(buyerChoice === fruits[i]) {
document.write(buyerChoice);
} else if (buyerChoice !== fruits[i]){
document.write("Sorry, " +buyerChoice+ " is out of season.");
break;
}
}
I believe the problems lies in the else-if
statement because every time I type in an item that exists in my variable, it will return //appleSorry, apple is out of season
, thus meeting both conditions.
I'm stumped. I guess the bottom line is how to effectively match a string from a prompt to an array, testing each item and how to parse an array if a prompted string doesn't exist.
Upvotes: 0
Views: 91
Reputation: 17656
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
var fruits = ["apple", "orange", "banana"];
var outOfSeason = false;
for(fruit in fruits) {
if(buyerChoice === fruits[fruit]) {
matched = true;
break;
}
}
if(! outOfSeason){
document.write(buyerChoice);
}
else{
document.write("Sorry, " +buyerChoice+ " is out of season.");
}
Upvotes: 0
Reputation: 708
// let the fruits be a global var instead of recreating it every time you call the function below
var fruits = ["apple", "orange", "banana"];
function askBuyerForFruit() {
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
for (var i = 0; i < fruits.length; i++) {
if (fruits[i] === buyerChoice) {
document.write(buyerChoice);
// get out of the function if found;
return;
}
}
// fallback if no matching fruit found
document.write("Sorry, " +buyerChoice+ " is out of season.");
}
Hope this helps :)
Upvotes: 1
Reputation: 2336
Not 100% sure what the for loop is trying to accomplish but you could use indexOf
var buyerChoice = prompt("Enter a either apple, orange, or banana:", "");
var fruits = new Array ("apple", "orange", "banana");
var matchedIndex = fruits.indexOf(buyerChoice);
if (matchedIndex < 0) { //did not match
document.write("Sorry, " +buyerChoice+ " is out of season.");
} else {
document.write(buyerChoice)
}
Upvotes: 1
Reputation: 4906
your for-loop isn't logical at all. Therefore items
wont work if it's undefined.
here's a possible solution
var outofseason = true;
for(i=0; i < fruits.length; i++) {
if(buyerChoice === fruits[i]) {
outofseason = false;
break;
}
}
if ( outofseason ) {
document.write("Sorry, " +buyerChoice+ " is out of season.");
}
else {
document.write(buyerChoice);
}
Upvotes: 1
Reputation: 154818
In the first iteration, the entered fruit either is or is not equal to "apple". But if it isn't "apple" the first iteration (but e.g. "orange"), then that does not mean "orange" is not available at all.
You should keep track whether you've matched anything (through using a variable), and only if after the loop nothing has been matched, then the entered fruit is indeed not available.
Upvotes: 2