javascript access the counter of a for in loop -


how can access counter of for..in loop?

i have array , object. want iterate on object properties while doing same array, without explicitly declaring counter.

var colors = ['red','yellow','purple','blue'];  var flowers = {'rose':'','sunflower':'','violet':'','hydrangea':''};  (prop in flowers) {     flowers[prop] = colors[i]; } 

follow question. if not possible, how create own loop functionality require. here's how it's working find i'm doing , want create reusable.

var colors = ['red','yellow','purple','blue'];  var flowers = {'rose':'','sunflower':'','violet':'','hydrangea':''};  var = 0; (prop in flowers) {     flowers[prop] = colors[i];     i++; } 

(ecmascript 2015 changes things, see update @ end of answer.)

i have array , object. want iterate on object properties while doing same array, without explicitly declaring counter.

i don't believe can. moreover, it's important understand properties in object have no order. seem assuming you'll "rose", "sunflower", etc. not guaranteed. many engines visit object property names in order in properties added object, , order in literal properties in object initializer added object is (as of es5 couple of years back) specified, visiting them in particular order in for-in not specified behavior (similarly, object.keys not sorted in particular way), , correct engine can visit them in order wants.

as such, array , object you've shown, have no reliable way map properties array entries.


as of ecmascript 2015 (es6), object properties have order now:

  1. let keys new empty list.
  2. for each own property key p of o integer index, in ascending numeric index order
    • add p last element of keys.
  3. for each own property key p of o string not integer index, in property creation order
    • add p last element of keys.
  4. for each own property key p of o symbol, in property creation order
    • add p last element of keys.
  5. return keys.

okay, know they'll visited in "creation" order, in order created object initializer? news: object initializers processed in source code order, that's deterministic. rose comes before sunflower, etc.

this means while still can't want without explicitly declaring , maintaining index variable, can relate array , object reliably:

// works of es6 var colors = ['red','yellow','purple','blue'];  var flowers = {'rose':'','sunflower':'','violet':'','hydrangea':''};  let = 0; (prop in flowers) {     flowers[prop] = colors[i++]; } 

i'm not suggesting doing it, it's possible now, on compliant engines.


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

ios - Change Storyboard View using Seague -