【问题标题】:How to check multiple arrays at once?如何一次检查多个数组?
【发布时间】:2020-08-17 19:51:28
【问题描述】:

我有这个代码。它检查auctions[0] 是否存在,如果存在,它会获取该值并将其发送并继续到下一个数字。如果不是,它会移动到下一个数字并做同样的事情。我需要它来检查它是否存在,直到它达到第 30 号

有没有什么替代品可以减少体积和杂乱?

if (ahValue.auctions[0]){
    var itemName = ahValue.auctions[0].item_name
    var itemLore = ahValue.auctions[0].item_lore
    var itemTier = ahValue.auctions[0].tier
    var itemSeller = ahValue.auctions[0].auctioneer
    var itemBids = ahValue.auctions[0].bids.length
    console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}
if (ahValue.auctions[1]){
    var itemName = ahValue.auctions[1].item_name
    var itemLore = ahValue.auctions[1].item_lore
    var itemTier = ahValue.auctions[1].tier
    var itemSeller = ahValue.auctions[1].auctioneer
    var itemBids = ahValue.auctions[1].bids.length
    console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}

//copy and paste until it reaches 30

if (ahValue.auctions[30]){
    var itemName = ahValue.auctions[30].item_name
    var itemLore = ahValue.auctions[30].item_lore
    var itemTier = ahValue.auctions[30].tier
    var itemSeller = ahValue.auctions[30].auctioneer
    var itemBids = ahValue.auctions[30].bids.length
    console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
}

【问题讨论】:

标签: javascript json


【解决方案1】:

使用for 循环:

for(let i = 0; i <= 30; i++) {
     if (ahValue.auctions[i]){
        var itemName = ahValue.auctions[i].item_name
        var itemLore = ahValue.auctions[i].item_lore
        var itemTier = ahValue.auctions[i].tier
        var itemSeller = ahValue.auctions[i].auctioneer
        var itemBids = ahValue.auctions[i].bids.length
            

        console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
     }
}

【讨论】:

  • 我建议将 for 循环的条件更改为:i
  • @SandroSchaurer 我同意,但问题要求循环到30
【解决方案2】:

试试这样的。

auctions.length 这将返回数组的长度,这将帮助您遍历所有元素。

这是运行代码sn-p。

var auctions = [];
auctions[0] = { "item_name" : "item_name1",  "item_lore" : "item_lore1", "tier" : "tier1",  "auctioneer" : "auctioneer1" , "bids":"bids1"};
auctions[1] = { "item_name" : "item_name2",  "item_lore" : "item_lore2", "tier" : "tier2",  "auctioneer" : "auctioneer2" , "bids":"bids2"};


for(var i = 0; i < auctions.length; i++){
 if(auctions[i]){
          console.log(auctions[i].item_name);
 }
}

您的完整代码将如下所示:

for(let i = 0; i <= ahValue.auctions.length; i++) {
     if (ahValue.auctions[i]){
        var itemName = ahValue.auctions[i].item_name
        var itemLore = ahValue.auctions[i].item_lore
        var itemTier = ahValue.auctions[i].tier
        var itemSeller = ahValue.auctions[i].auctioneer
        var itemBids = ahValue.auctions[i].bids.length
            

        console.log(`${itemName}${itemLore}${itemTier}${itemSeller}${itemBids}`)
     }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2012-01-31
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    相关资源
    最近更新 更多