0

I have an array like this:

elements = {
    opinions: ['p31/php/endpoint.php?get=opinions'], // function to call and API endpoint, php/endpoint.php
    top3positive: ['p31/php/endpoint.php?get=top3positive'], // function to call andAPI endpoint, php/endpoint.php
    top3negative: ['p31/php/endpoint.php?get=top3negative'], // function to call andAPI endpoint, php/endpoint.php
};

How do I point to the 1 first array. If I do alert(elements[0]); it is not returning opinions as I would expect. What am I doing wrong?

I need to point to the array index based on its order 0,1,2 etc.

Thanks

2 Answers2

3

The {} notation creates objects, not arrays. Hence, they are not integer-indexed and their properties have to be accessed using a classic dot notation or using [].

If you want an array, this is the correct way to build it:

elements = [
    'p31/php/endpoint.php?get=opinions', // function to call and API endpoint, php/endpoint.php
    'p31/php/endpoint.php?get=top3positive', // function to call andAPI endpoint, php/endpoint.php
    'p31/php/endpoint.php?get=top3negative', // function to call andAPI endpoint, php/endpoint.php
];

If you leave your object as is in your question, you can access e.g. its first element like this:

elements.opinions;

or

elements['opinions'];

Micro-edit

I left a trailing comma in the array, which is fine in modern browsers but can cause some issues in older IEs. Just to be clear :)

whatyouhide
  • 15,897
  • 9
  • 57
  • 71
0

Since you set them as objects, you can access them as:

elements['opinions'];
elements['top3positive'];
elements['top3negative'];

If you want to set them as an array then:

var elements=['p31/php/endpoint.php?get=opinions','p31/php/endpoint.php?get=top3positive','p31/php/endpoint.php?get=top3negative'];

Then when you want to access to the item in array you can do:

elements[0];
Caner Akdeniz
  • 1,862
  • 14
  • 20
  • Yes I understand this, but as I said I need to access them by index with a number. How do I convert this object into an array –  Nov 06 '13 at 22:52