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!

3
  • I read that it's for declaring two-dimensional arrays: stackoverflow.com/a/18163289/1503127 Commented Aug 27, 2015 at 9:31
  • 1
    You are missing the =. And var x = [[]]; is just declaring an array with an array in the first index. Commented Aug 27, 2015 at 11:43
  • Yup I've now seen what I've done wrong. Thanks for pointing this out Commented Aug 27, 2015 at 12:06

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

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 i-programmer.info/programming/javascript/… and i-programmer.info/programming/javascript/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.