JS中遍历对象属性的四种方法
Posted lyd312
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS中遍历对象属性的四种方法相关的知识,希望对你有一定的参考价值。
Object.keys()、Object.values()、Object.entries()、for...in、Map
(1)Object.keys():
let ex1 = {c1: ‘white‘,c2: ‘black‘}
let ex2 = {c3: ‘green‘,c4: ‘yellow‘}
Object.setPrototypeOf(ex1 ,ex2 ):Obejct.keys(ex2 ) === [‘c3‘,‘c4‘] ex2[‘c3‘] === ‘green‘
(2)Object.values():
let ex1 = {c1: ‘white‘,c2: ‘black‘}
let ex2 = {c3: ‘green‘,c4: ‘yellow‘}
Obejct.values(ex2 ) === [‘green‘,‘yellow‘]
(3)Object.entries():
let ex1 = {c1: ‘white‘,c2: ‘black‘}
let ex2 = {c3: ‘green‘,c4: ‘yellow‘}
Obejct.values(ex2 ) === [[c3,‘green‘],[‘c4‘,‘yellow‘]]
(4)for...in:
let ex1 = {c1: ‘white‘,c2: ‘black‘}
let ex2 = {c3: ‘green‘,c4: ‘yellow‘}
let cArry = [];
for(let key in ex1){cArry.push(key)}
(5)Map实例提取属性之或键值对:Map.prototype.values() === Object.values();Map.prototype.entries() === Object.entries()
let gr = {he: ‘hello‘,bl: ‘blog‘}
let grMap = new Map(Object.entries(gr))
grMap.get(‘he‘) === ‘hello‘;grMap.get(‘bl‘) === ‘blog‘
注意:
(1)属性的顺序排列有两种方法:Object.getOwnProtpertyNames、Reflect.ownKeys
(2)数字:属性类型为数字类型时,按数字从大到小排序
(3)字符串:属性类型为字符串时,按时间的先后顺序排序
(4)Symbol:当属性类型为Symbol时,按时间的先后顺序排序
(5)如果需要有序集合,建议将数据存储到数组或Set中。
(6)Object.values()和Object.entries()返回数据的顺序是不确定。
以上是关于JS中遍历对象属性的四种方法的主要内容,如果未能解决你的问题,请参考以下文章