JS - 遍历对象属性

栗子:

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;

方法一 for in

用于遍历对象的可枚举属性,包括自有属性、继承自原型的属性(不含Symbol属性)

for(var key in obj){
  console.log(key);
}
//输出:name, career, protoPer1, protoPer2

方法二 Object.keys(xx)/Object.values(xx)

返回一个数组,元素均为对象自有的可枚举属性(不含继承的、Symbol属性)

console.log(Object.keys(obj));
console.log(Object.values(obj));
//输出:["name", "career"]
//输出:[ "Poly", "it"]

Object.getOwnProperty

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

console.log(Object.getOwnPropertyNames(obj));
//输出:["name", "career", "age"]
posted @ 2019-09-05 11:05  sunidol  阅读(35945)  评论(0编辑  收藏  举报