function checkStore(string) {
for (var i = 0; i < BookStore.length; i++) {
if (BookStore[i].title === string) {
prompt('We found your book! ' + string + ', by ' + BookStore[i].author +
'. It costs ' + BookStore[i].price +
' would you like to add it to your cart?');
} else {
alert('Sorry ' + string + ' was not found, try another title?');
}
}
}
This is what happens lets say the BookStore.length = 6. If BookStore[i].title === string
is true at index 4 this is what i get
'Sorry ' + string + ' was not found, try another title?'
'Sorry ' + string + ' was not found, try another title?'
'Sorry ' + string + ' was not found, try another title?'
'Sorry ' + string + ' was not found, try another title?'
'We found your book! ' + string + ', by ' + BookStore[i].author +
'. It costs ' + BookStore[i].price +
' would you like to add it to your cart?'
'Sorry ' + string + ' was not found, try another title?'
How do i get it to just print 'Sorry ' + string + ' was not found, try another title?'
once when not true and
'We found your book! ' + string + ', by ' + BookStore[i].author +
'. It costs ' + BookStore[i].price +
' would you like to add it to your cart?'
by itself when true?
Thank you!
A solution with Array.prototype.some()
:
function checkStore(string) {
var book;
if (BookStore.some(function (b) {
return b.title === string && (book = b);
})) {
prompt('We found your book! ' + string + ', by ' + book.author + '. It costs ' + book.price + ' would you like to add it to your cart?');
} else {
alert('Sorry ' + string + ' was not found, try another title?');
}
}