1

Given

var input[[]];

$('some_selector').each(function() {
   var outer, inner; 
   outer=$(this).parent().attr('some_property');
   inner=$(this).attr('a_property');
   input[outer].push(inner);
});

An error is encountered during the push function. Is it because the specific input[outer] is not declared as array?

Also, the value of outer is not necessarily sorted. So within the loop, outer can sequentially have values of: "property1","property2","property1","property3","property2"...

In PHP terms, is there something equivalent to:

foreach () {
    $input[$outer][]=$inner;
}

Thanks!

alds
  • 525
  • 9
  • 19

1 Answers1

2

If outer has values like "property1", etc., then input isn't an array. It's an object. Unlike PHP, there are no associative arrays in Javascript.

Try:

var input = {};

And yes, you'll need to create an array before pushing to it. You can do that in one "maybe it exists, maybe it doesn't" step like so:

input[outer] = input[outer] || [];

and then push as before:

input[outer].push(inner);
Paul Roub
  • 36,322
  • 27
  • 84
  • 93
  • It works!!! Thanks a lot Paul. This was an AHA moment for me and pointed me to the right direction. Just got to understood nature of Javascript arrays (index and associative) and objects. For those who are confused like I was, you can read http://www.i-programmer.info/programming/javascript/2865-javascript-data-structures-the-array-object.html and http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html – alds Aug 27 '15 at 09:30