[英]Else statement still running when if statement is true with google script
[英]Else statement still running when if statement is true
我具有搜索功能,可讓您搜索加密貨幣,並且嘗試將其存儲在如果所搜索的參數/硬幣與硬幣或符號的API標題不匹配的地方,則會彈出一個警告框,告訴您用戶重試。
我遇到的問題是,如果if語句為true並且存在匹配項,則無論如何都會彈出else語句/警報框。 這是我的axios請求中的代碼:
cryPrice(param){
axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=0`)
.then(res => {
const cryptos = res.data;
const price = []
for(let title in cryptos){
const cryptoTitle = cryptos[title].name.toUpperCase();
const cryptoSymbol = cryptos[title].symbol.toUpperCase();
if(cryptoTitle === param || cryptoSymbol === param){
price.push(cryptos[title].price_usd);
}else{
alert("Please try again");
break;
}
}
this.setState({
priceResults: price
})
})
}
您的代碼循環遍歷數組中的每個單個項目,一旦遇到不匹配的項目,它將發出警報並中斷循環
您可能想要的更像是
cryPrice(param){
axios.get(`https://api.coinmarketcap.com/v1/ticker/?limit=0`)
.then(res => {
const priceResults = res.data
.filter(item => [item.name.toUpperCase(), item.symbol.toUpperCase()].includes(param))
.map(item => item.price_usd);
if (priceResults.length) {
this.setState({priceResults});
} else {
alert("Please try again");
}
})
}
您會在某些元素上找到匹配項,但會相互警告,所有與param不匹配的元素。 您可能應該僅在循環執行停止並且沒有貨幣匹配時發出警報。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.