user2426701
user2426701

Reputation:

Get array count in Javascript

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

Upvotes: 0

Views: 124

Answers (2)

Caner Akdeniz
Caner Akdeniz

Reputation: 1862

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];

Upvotes: 0

whatyouhide
whatyouhide

Reputation: 16781

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 :)

Upvotes: 3

Related Questions