在收到 API 的响应后尝试将元素添加到数组中

Posted

技术标签:

【中文标题】在收到 API 的响应后尝试将元素添加到数组中【英文标题】:Trying to add elements to an array after receiving an response from an API 【发布时间】:2022-01-21 08:47:17 【问题描述】:

所以基本上我与在线视频扑克(jacks 或更好的)API 交互,我想创建一个自动为我做出决定的机器人,api 请求工作正常,但我希望机器人做出决定为我保留/持有 initalHand 的卡片,下面是我的代码

let bodyReq = variables:currency:currency,amount:betAmount,query: "mutation VideoPokerBet($amount: Float!, $currency: CurrencyEnum!) \n  videoPokerBet(amount: $amount, currency: $currency) \n    ...CasinoBet\n    state \n      ...CasinoGameVideoPoker\n    \n  \n\n\nfragment CasinoBet on CasinoBet \n  id\n  active\n  payoutMultiplier\n  amountMultiplier\n  amount\n  payout\n  updatedAt\n  currency\n  game\n  user \n    id\n    name\n  \n\n\nfragment CasinoGameVideoPoker on CasinoGameVideoPoker \n  playerHand \n    suit\n    rank\n  \n  initialHand \n    suit\n    rank\n  \n  handResult\n\n"

let bodyHeld = variables:identifier:identifier,held:[],query: "mutation VideoPokerNext($held: [VideoPokerNextHeldInput!]!, $identifier: String!) \n  videoPokerNext(held: $held, identifier: $identifier) \n    ...CasinoBet\n    state \n      ...CasinoGameVideoPoker\n    \n  \n\n\nfragment CasinoBet on CasinoBet \n  id\n  active\n  payoutMultiplier\n  amountMultiplier\n  amount\n  payout\n  updatedAt\n  currency\n  game\n  user \n    id\n    name\n  \n\n\nfragment CasinoGameVideoPoker on CasinoGameVideoPoker \n  playerHand \n    suit\n    rank\n  \n  initialHand \n    suit\n    rank\n  \n  handResult\n\n"

async function vpokerBet() 
    try
    running.style.color = "lightgreen"
    let respData;
    while(true) 
        respData = await (await fetch(url, 
            method: "POST",
            headers: 
                "Content-Type": "application/json",
                "Accept": "application/json",
                "x-access-token": apikey,
            ,
            body: JSON.stringify(
                bodyReq
            )
        )).json()
        do
        respData = await (await fetch(url, 
            method: "POST",
            headers: 
                "Content-Type": "application/json",
                "Accept": "application/json",
                "x-access-token": apikey,
            ,
            body: JSON.stringify(
                bodyHeld
            )
        )).json()while(respData.data.videoPokerBet.active == true)

基本上假设它返回一个响应,其中 InitalHand 的数据已绘制 4 K,我想将这些卡片附加到 let bodyHeld 中的 held: [] 数组,所以我的下一个请求将保留那些 4 K ,我正在努力找出我该怎么做,任何帮助将不胜感激! , 谢谢 ! :)

【问题讨论】:

【参考方案1】:

我只是在我要添加的卡片中放了一个.push,下面是代码

if (respData.data.videoPokerBet.state.initialHand[0].rank == "Q")

   bodyHeld.variables.held.push(respData.data.videoPokerBet.state.initialHand[0])

【讨论】:

以上是关于在收到 API 的响应后尝试将元素添加到数组中的主要内容,如果未能解决你的问题,请参考以下文章

如何将响应 API 中的数组映射到响应中的选择元素?

如何将嵌套数组添加到我的模型类

没有将 Cors 标头添加到响应中

如何使选项卡和选项卡栏视图在颤动中动态化,以便它能够响应来自 api 的响应?

Vue.js 将对象添加到现有数组

防止在数组中添加重复值