Carter Sifferman
Carter Sifferman

Reputation: 53

How to access attributes of object literals in javascript array

Can you tell me what is wrong with this javascript code? It seems like the countries array is not getting initialized correctly, because it doesn't even make it past the initialization to the second document.write("test2"); line:

<script>
document.write("test1");
var countries;
countries = [
    {
        name: 'France',
        continent: 'Europe',
        cities: ['Paris', 'Nice'],
        photos: [france1.jpg, france2.jpg]
    },
    {
        name: 'Mexico',
        continent: 'North America',
        cities: ['Tijuana', 'Cancun', 'Mexico City'],
        photos: [mexico1.jpg, mexico2.jpg, mexico3.jpg]
    },
    {
        name: 'China',
        continent: 'Asia',
        cities: ['Beijing', 'Shanghai', 'Hong Kong'],
        photos: [china1.jpg, china2.jpg]
    }
];
document.write("test2");
document.write(countries[0].name);

</script>

Upvotes: 0

Views: 58

Answers (2)

agent3bood
agent3bood

Reputation: 1354

You have to qoute the strings (‘france1.jpg,‘)in the photos variable.

Upvotes: 0

Tigger
Tigger

Reputation: 9120

The 'photos' need to be quoted. For example,

{
    name: 'France',
    continent: 'Europe',
    cities: ['Paris', 'Nice'],
    photos: ['france1.jpg', 'france2.jpg']
}

A quick check of your Javascript error console should have shown you this.

Upvotes: 1

Related Questions