无法访问对象的属性-对象

时间:2018-10-31 14:07:56

标签: javascript node.js javascript-objects discord.js

我正在开发我的不和谐机器人,并且正在执行“帮助”命令。我首先有一个commands数组,如果他们想要特定命令的帮助,我必须添加比我想更多的代码行。我想知道是否可以像这样将对象放入对象内部:

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    }
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

或者我还需要做其他事情,因为当我这样做

for(var name in commands1){
    embed.addField("Command:", name)
}

这将列出所有可用的命令。但是,我无法访问用法或说明,因此我尝试这样做:

.addField("Usage:", name.usage)
.addField("Description:", name.description)

(它表示未定义)是我访问错误还是无法将对象放入对象中?抱歉,我对此还比较陌生:)谢谢。

3 个答案:

答案 0 :(得分:1)

我发现了这个名字。是字面意义,它认为我想要使用commands1.coinflip时尝试访问commands1.name。所以我通过这样做解决了这个问题

console.log(commands1.coinflip.usage)

答案 1 :(得分:1)

您正在使用for...in循环,该循环遍历数组的索引。但是实际情况是您有object。因此,在这种情况下,我建议您这样做:

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    }
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

const keys = Object.keys(commands1); // #Output : ["coinflip", "diceroll"]

for(let key of keys){
   embed.addField("Command:", commands1[key].usage);
}

答案 2 :(得分:0)

不用担心成为新手,我们都从某个地方开始。

您的新手问题可能比我的要好!

const commands1 = {
    coinflip: {
        usage: prefix + "coinflip",
        description: `Flip a coin then guess what it landed on.`
    },
/* Added a missing , above */ 
    diceroll: {
        usage: prefix + "diceroll (number)",
        description: `Roll a die and guess what it lands on`
    }
};

for(var name in commands1){
    embed.addField("Command:", name);
    console.log(commands1[name].usage);
    console.log(commands1[name].description); /* You can Use your index to directly access the object thru the parent object. */ 
}