简体   繁体   English

json数组有一些问题

[英]Having some problems with a json array

exports.equipp = function(user, User, msg) {

    var itemname = msg.content.slice(8);

    User.find({id: user.id}, function(err, usser) {

        for(i = 0; i < usser[0].inventory.length; i++) {

            if (usser[0].inventory[i].name == itemname) {


                var Item = usser[0].inventory[i];

                for (j = 0; j < usser[0].equipped.length; j++) {

                    if (Item.type == usser[0].equipped[j].type) {

                    }
                    if (j == usser[0].equipped.length -1) {

                    }
                }
            } else {

                if (i == usser[0].inventory.length -1) {

                    msg.reply("You dont have that Item");

                }
            }
        }
    })
}

I'm having some porblems with it at the end at the if (j == usser[0].equipped.length -1) it never goes through and hence never adds an item to a empty inventory. 我在if (j == usser[0].equipped.length -1)的末尾有一些问题,它永远不会通过,因此也永远不会在空库存中添加任何项目。 I have items which atm only contain Name, Dmg, and Type im checking if the types match then if they do i add the item to the equipped array and remove it from the items array and vice versa for the item already equipped and when there is no item with that type in the array i need to just add it and remvoe it from the other array but my code fails at the point stated above an array of json objects { "type": "Healm", "armor": 4, "name": "Starter Healm" }, 我有一些atm仅包含Name,Dmg和Type im的项目,检查类型是否匹配,然后将它们添加到配备的阵列中,并将其从items阵列中删除,反之亦然,对于已配备的项目以及何时存在数组中没有该类型的项,我只需要添加它并从另一个数组中删除它,但是我的代码在上述json对象数组{“ type”:“ Healm”,“ armor”:4, “ name”:“入门级医疗”},

Instead of this : 代替这个:

    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        } else {
            if (i == usser[0].inventory.length -1) {
                msg.reply("You dont have that Item");
            }
        }
    }

Do: 做:

    for(i = 0; i < usser[0].inventory.length; i++) {
        if (usser[0].inventory[i].name == itemname) {
            var Item = usser[0].inventory[i];
            // rest of code ...
        }
    }
    if (!Item) {
        msg.reply("You dont have that Item");
    }

The determining factor whether you found the item is that you have defined Item . 是否找到物料的决定因素是您已定义Item It after the loop you find that Item was not set, you know the item was not in the list. 循环之后 ,您发现未设置Item ,您知道该项目不在列表中。 This obviously also works when the list is empty. 当列表为空时,这显然也适用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM