【问题标题】:Cannot access object's properties - objects无法访问对象的属性 - 对象
【发布时间】:2018-10-31 14:07:55
【问题描述】:

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

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)

(它说未定义)我访问它是否错误,或者我不能将对象放入对象中。抱歉,我对此比较陌生 :) 谢谢。

【问题讨论】:

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


    【解决方案1】:

    我发现了那个名字。是字面意思,当我想要commands1.coinflip 时,它认为我正在尝试访问commands1.name。所以我通过这样做来修复它

    console.log(commands1.coinflip.usage)
    

    【讨论】:

    • 如果您以任何一种方式对硬币翻转进行硬编码,您都应该使用点表示法。如果您将它作为变量传递(例如name),那么您可以使用查找语法(例如commands1[name].usage)
    【解决方案2】:

    您正在使用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);
    }
    

    【讨论】:

    • 谢谢,它与我所拥有的一样好用,我只使用 for 循环查看命令名称,以便它可以列出所有命令。我寻找他们输入的特定命令的部分只是commands1[commandname].usage,它就像一个魅力,我消除了很多代码行。
    【解决方案3】:

    别担心自己是新人,我们都是从某个地方开始的。

    你的新手问题可能比我的好!

    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. */ 
    }
    

    【讨论】:

    • 仅供参考:我的答案看起来与上面 Jai 的相同......但是,资源更容易+性能更好。我不会在内存中放置不必要的数据(例如:键。)虽然对于这个简单的例子......任何一种解决方案都很好 - 当解决方案扩展时......更少就是更多。
    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 2016-07-22
    • 2018-09-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多