How to list the properties of a javascript object

本篇參考 stackoverflowHow to list the properties of a javascript object

要如何知道 Javascript 物件擁有哪些 proerty?

var dog = {
  name: 'Lucky', 
  age: 3, 
  breeds: 'Shiba Inu'
};

上面是一個小狗的物件,裡面有一些自訂的屬性 'name', 'age', 'breeds' 等等...

那要怎麼在程式中知道這些屬性呢?

比較新的瀏覽器(IE9, FireFox, Chrome...)可直接使用 Object.keys 這個方法

var keys = Object.keys(dog);

或者自己寫

var getKeys = function(obj){
   var keys = [];
   for(var key in obj){
      keys.push(key);
   }
   return keys;
}
var keys = getKeys(dog);

這樣 keys 就會是一個有所有屬性的陣列

keys = ["name", "age", "breeds"];

參考文章: