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()返回数据的顺序是不确定。

上一篇:Sublime Text 2 HTML代码缩进 美化HTML代码


下一篇:sublime text 多行代码注释快捷键