简体   繁体   中英

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. 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" },

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 . It after the loop you find that Item was not set, you know the item was not in the list. This obviously also works when the list is empty.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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