JS four methods traversal object properties

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 of Example extracted attributes or key-value pairs: 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'

note:

(1) arranged in the order of attributes in two ways: Object.getOwnProtpertyNames, Reflect.ownKeys

(2) number: The attribute type is numeric type, press descending order

(3) string: a string attribute type, sorted by chronological order

(4) Symbol: When the attribute type Symbol, sorted by chronological order

(5) If you need an ordered set, it is recommended to store the data into an array or a Set.

Sequence (6) Object.values ​​() and Object.entries () returns the data is uncertain.

Guess you like

Origin www.cnblogs.com/LYD312/p/12071020.html