Object.entries()方法返回一个给定对象自身可枚举属性的键值对数组,其排列与使用for…in循环遍历该对象时返回的顺序一致(区别在于for-in 循环也枚举原型链中的属性)。
通俗点就是Object.entries()可以把一个对象的键值对以数组的形式遍历出来 结果和for…in一致 但不会遍历原型属性
示例1—传入对象
const obj = {foo:‘bar’,baz:‘abc’}
console.log(Object.entries(obj)); //[[‘foo’,‘bar’],[‘baz’,‘abc’]]
示例2.1 —数组
const arr = [1,2,3]
console.log(Object.entries(arr));//[[‘0’,1],[‘1’,‘2’],[‘2’,‘3’]]
示例2.1—数组(数组中包含对象)
const arr = [{a:1},2,3]
console.log(Object.entries(arr));//[[‘0’,{a:1}],[‘1’,‘2’],[‘2’,‘3’]]
#####2.3 数组(数组中的值全部为对象)
const arr = [{a:1},{b:2},{c:3}]
console.log(Object.entries(arr));//[[‘0’,{a:1}],[‘1’,{b:2}],[‘2’,{c:3}]]
示例3—字符串
const str = “123”
console.log(Object.entries(str));//[[‘0’,‘1’],[‘1’,‘2’],[‘2’,‘3’]]
示例4 —数字、浮点数
const num = 123;
console.log(Object.entries(num)); //[]
const float = 12.3
console.log(Object.entries(float)); //[]
示例5—将Object转化为Map
new Map()构造函数接收一个可迭代的entries。借助Object.entries方法你可以很容易的将Object转换为Map:
const obj2 = {foo:‘bar’,baz:‘abc’}
console.log(Object.entries(obj2)); //[[‘foo’,‘bar’],[‘baz’,‘abc’]]
const map = new Map(Object.entries(obj2));
console.log(map); // Map {‘foo’=>‘bar’,‘baz’=>‘abc’}