gpt4 book ai didi

javascript - 我只想让这个函数提醒该书在遍历 bookStore 数组后一次没有找到,而不是在每个索引处。

转载 作者:行者123 更新时间:2023-12-03 09:09:29 24 4
gpt4 key购买 nike

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 find, 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?');
}
}

关于javascript - 我只想让这个函数提醒该书在遍历 bookStore 数组后一次没有找到,而不是在每个索引处。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32124258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com