2010-03-03 98 views
2

我有JavaScript中的下一個代碼。我刪除了一些不必要的項目,因爲它耗時很長。For循環的對象?

var options = { 
    dhcode: true, 
    commands: { 
     bold: { 
      enabled: true, 
      view: true, 
      exec: true, 
      cmd: 'bold', 
      param: null 
     }, 
     italic: { 
      enabled: true, 
      view: true, 
      exec: true, 
      cmd: 'italic', 
      param: null 
     }, 
     underline: { 
      enabled: true, 
      view: true, 
      exec: true, 
      cmd: 'underline', 
      param: null 
     } 
    } 
} 

現在我想在options.commands對象中獲取al數據。但是我所嘗試的一切都不起作用。這是我正在嘗試:

for(var i=0;i<options.commands.length;i++) { 
alert(options.commands[i].cmd); 
} 

請幫助我。

回答

7

.length是數組的屬性,你擁有的是一個對象。

嘗試:

for(var key in options.commands) { 
    alert(options.commands[key].cmd); 
} 
+0

謝謝!有用! @Justen&Jage:也謝謝! – Timo 2010-03-03 18:00:28

1
for(var i in options.commands){ 
    alert(i); //bold, italic, underline 
    alert(options.commands[i].cmd); 
}