js中幾種遍歷對象的方法,包括for in、Object.keys、Object.getOwnProperty,它們在使用場景方面各有不一樣。數組
主要用於遍歷對象的可枚舉屬性,包括自有屬性、繼承自原型的屬性spa
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("For In : "); for(var a in obj) console.log(a);
輸出以下
prototype
返回一個數組,元素均爲對象自有的可枚舉屬性code
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("Object.keys:") console.log(Object.keys(obj));
輸出以下:
對象
用於返回對象的自有屬性,包括可枚舉和不可枚舉的blog
var obj = {"name":"Poly", "career":"it"} Object.defineProperty(obj, "age", {value:"forever 18", enumerable:false}); Object.prototype.protoPer1 = function(){console.log("proto");}; Object.prototype.protoPer2 = 2; console.log("Object.getOwnPropertyNames: "); console.log(Object.getOwnPropertyNames(obj));
輸出以下:
繼承