(for..in)、Object.keys()和Object.getOwnPropertyNames(),for...of

Object.keys(obj),返回一个数组,数组里是该obj可被枚举的所有属性。请看示例:

示例一:

function Pasta(grain, width, shape) {
          this.grain = grain;
          this.width = width;
          this.shape = shape;
          this.toString = function () {
                  return (this.grain + ", " + this.width + ", " + this.shape);
          }
  }
  console.log(Object.keys(Pasta)); //console: []
  var spaghetti = new Pasta("wheat", 0.2, "circle");
  console.log(Object.keys(spaghetti)); //console: ["grain", "width", "shape", "toString"]

示例二:

var arr = ["a", "b", "c"];
   console.log(Object.keys(arr)); // console: ["0", "1", "2"]
   var obj = { 0 : "a", 1 : "b", 2 : "c"};
   console.log(Object.keys(obj)); // console: ["0", "1", "2"]
   var an_obj = { 100: "a", 2: "b", 7: "c"};
   console.log(Object.keys(an_obj)); // console: ["2", "7", "100"]
   var my_obj = Object.create({}, { getFoo : { value : function () { return this.foo } } });
   my_obj.foo = 1;
   console.log(Object.keys(my_obj)); // console: ["foo"]

js中几种遍历对象的方法,包括for in、Object.keys、Object.getOwnProperty,它们在使用场景方面各有不同。

for in

主要用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性

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);

Object.keys

返回一个数组,元素均为对象自有的可枚举属性

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));

Object.getOwnProperty

用于返回对象的自有属性,包括可枚举和不可枚举的

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));

for..of

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 of : ");
for(var a of Object.entries(obj)) console.log(a);