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?');
}
}
}
这就是发生的情况,可以说BookStore.length =6。如果
BookStore[i].title === string
在索引4处为true,这就是我得到的'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?'
如果不正确,我如何只打印一次
'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?'
本身何时成立?
谢谢!
最佳答案
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?');
}
}