JS中遍歷對象屬性的四種方法

Object.keys()、Object.values()、Object.entries()、for...in、Map數組

(1)Object.keys():prototype

  let ex1 = {c1: 'white',c2: 'black'}blog

  let ex2 = {c3: 'green',c4: 'yellow'}排序

Object.setPrototypeOf(ex1 ,ex2 ):Obejct.keys(ex2 ) === ['c3','c4']           ex2['c3'] === 'green'字符串

(2)Object.values():get

  let ex1 = {c1: 'white',c2: 'black'}it

  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()返回數據的順序是不肯定。

相關文章
相關標籤/搜索