码迷,mamicode.com
首页 > Web开发 > 详细

JS中遍历对象属性的四种方法

时间:2019-12-20 01:05:01      阅读:707      评论:0      收藏:0      [点我收藏+]

标签:type   log   otp   prot   数字类型   val   new   数据   hit   

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中遍历对象属性的四种方法

标签:type   log   otp   prot   数字类型   val   new   数据   hit   

原文地址:https://www.cnblogs.com/LYD312/p/12071020.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!