gpt4 book ai didi

javascript - 测试不同值的许多条件的干净方法?

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

所以,我想针对不同的值测试许多条件...现在只是一堆 if,else 语句...

但它看起来很难看,我确信一定有更好的方法......

有什么想法吗?

我想也许使用循环,但是或者将所有变量放入一个数组中,但我不知道如何......

谢谢!

var dataObject = {}

if (newState.playerId){
dataObject["filter[player_id]"] = newState.playerId
}else{
dataObject["filter[player_id]"] = this.state.playerId
}

if (newState.pageLimit){
dataObject ["page[limit]"] = newState.pageLimit
}else{
dataObject["page[limit]"] = this.state.pageLimit
}

if (newState.timeFrom){
dataObject["time[from]"] = newState.timeFrom
}else{
dataObject["time[from]"] = this.state.timeFrom
}

if (newState.timeTo){
dataObject["time[to]"] = newState.timeTo
}else{
dataObject["time[to]"] = this.state.timeTo
}

if (newState.gameId){
dataObject["filter[game_id]"] = newState.gameId
}else{
dataObject["filter[game_id]"] = this.state.gameId
}

if (newState.customerId){
dataObject["filter[customer_id]"] = newState.customerId
}else{
dataObject["filter[customer_id]"] = this.state.customerId
}

if (newState.currency){
dataObject["filter[currency]"] = newState.currency
}else{
dataObject["filter[currency]"] = this.state.currency
}

if (newState.variant){
dataObject["filter[locale]"] = newState.locale
}else{
dataObject["filter[locale]"] = this.state.locale
}

if (newState.variant){
dataObject["filter[demo]"] = newState.demo
}else{
dataObject["filter[demo]"] = this.state.demo
}

最佳答案

使用 or (||) 运算符利用 short circuit evaluation ,例如

 dataObject["filter[player_id]"] = newState.playerId ||  this.state.playerId

关于javascript - 测试不同值的许多条件的干净方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31053478/

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