2016-11-23 99 views
0

我在node.js中寫一個機器人,我的命令在一個JSON表像這樣持有一種:解析JSON [Node.js的]

Commands = { 
    "exit": { 
    name: "exit", 
    desc: "exits the bot", 
    usage: "n/a", 
    func: function() { 
     process.exit(0); 
    } 
} 
} 

,我想知道我怎麼會循環通過命令表來得到這樣的命令的功能/名稱thigs所以其實我可以檢查是否命令是口語等

+0

是命令對象是數組嗎? – M14

回答

0

你可以通過使用在命令對象循環。

for (cmd in Commands) { 
    //Code to deal with each of the command should go here. 
    //cmd contains each of your commands. 
    //cmd.name, cmd.usage, cmd.func gives each of the property name 
    .... 
} 
+0

好吧,我剛剛啓動Node.JS,但是,如何訪問for循環外的cmd.name等? – MrBleach

+0

如果您查找任何特定的命令,那麼您可以將其分配給某個變量並使用它。 – Karpak

0

,如果你有

var Commands = { 
    'exit': { 
    name: 'exit', 
    desc: 'exits the bot', 
    usage: 'n/a', 
    func: function() { 
     process.exit(0); 
    } 
    } 
}; 

事遂所願

var key = "exit"; 
var name = Commands[key].name; <- this should be exit 
var result = Commands[key].func(); <- this calls the func 

更多錯誤檢查

var ref = Commands[key]; 
var name = ref != null ? ref.name : undefined; 
var result = ref != null ? ref.func() : undefined;