Javascript Array operations on string-index array -


this question has answer here:

it seems map, foreach, filter , sort of operators don't work string-indexed arrays so:

let = []; a['first element'] = 1; a['second element'] = 2; a['third element'] = 3; a.foreach(console.log) //undefined 

that's because it's not "string-indexed array." javascript doesn't have those. have there array (because used []) you're not using array, you're using object. (arrays objects; see a myth of arrays.) object property names. if you're not using array-ness of it, use {} instead of [] create it.

there couple of operations iterate property names:

  • you can array of object's own, enumerable property names via object.keys. there's object.getownpropertynames.
  • you can loop through enumerable properties (including inherited ones) for-in loop.
  • plain objects aren't iterable, can't use for-of, if want "string-indexed array" might @ map, iterable.

here couple of examples:

let = {};  a['first element'] = 1;  a['second element'] = 2;  a['third element'] = 3;  console.log("for-in:");  (let key in a) {    console.log(key);  }  console.log("object.keys:");  object.keys(a).foreach(key => console.log(key));


Comments

Popular posts from this blog

inversion of control - Autofac named registration constructor injection -

verilog - Systemverilog dynamic casting issues -

ios - Change Storyboard View using Seague -