Local variable not being recognized inside for loop – Javascript

I’m trying to reference a variable inside this for loop, but its not working. It recognizes the first variable in the line but anything beyond that it won’t recognize

        var farmsArray = Object.keys(farmsPath);
        var farmsList = new MessageEmbed()
            .setTitle("Available Farms")
            .setDescription("Where would you like to plant?")
            .setColor(0xFFF00);


        for(i=0; farmsArray[i] != undefined; i++){
            console.log(i);
            farmsList.addField(` ${farmsPath.farmsArray[i].name}`, farmsPath.farmsArray[i].size);
                 it recognizes this^          ^ but not this
        };

Can someone help me find out why? I’ve been trying for a while now and I can’t seem to figure out the issue.

32 thoughts on “Local variable not being recognized inside for loop – Javascript”

  1. Based on var farmsArray = Object.keys(farmsPath); I’ll imagine farmsPath is an object whose keys you want to iterate over.

    var farmsList = new MessageEmbed()
      .setTitle("Available Farms")
      .setDescription("Where would you like to plant?")
      .setColor(0xfff00);
    
    Object.keys(farmsPath).forEach((key) => {
      farmsList.addField(
        ` ${farmsPath[key].name}`,
        farmsPath[key].size,
      );
    });
    

    could be closer to what you’re looking for.

    Reply

Leave a Comment