⭐️ Object.entries

function Test() {
	this.a = 1;
  this.b = 2;
}
Test.prototype.c = 3;
Object.defineProperty(Test.prototype, 'd', {
	value: 4
});

var test = new Test();

var testArr = Object.entries(test);
for (const [key, value] of testArr) {
	console.log(key, value);
}

// 对比 for in
for (var key in test) {
	console.log(key, test[key]); // 原型上的可枚举属性也会被打印
}

Untitled

配合 map 使用

var obj = {
	a: 1,
  b: 2
}

var objArr = Object.entries(obj);
var map = new Map(objArr);
console.log(map);

Untitled

原理

Object.prototype.myEntries = function(obj) {
	var _pool = [];
  if (Object.prototype.toString.call(obj) === '[object Object]') {
  	for (var key in obj) {
    	if (Object.prototype.hasOwnProperty.call(obj, key)) {
      	_pool.push([key, obj[key]]);
      }
    }
  }
  return _pool;
};

var obj = {
	a: 1,
  b: 2
}
obj.__proto__.c = 3;

var objArr = Object.myEntries(obj);
console.log(objArr);

Untitled