0

I am trying to get the total size of my array to be the index of one part of an image carousel I am making. Each time I try to do this, the variable set get the length of the array doesn't seem to work.

These are my images:

var carouselImages = [
    {
        url : 'images/carousel/carousel1.jpg'
    },
    {
        url: 'images/carousel/carousel2.jpg'
    },
    {
        url: 'images/carousel/carousel3.jpg'
    },
    {
        url: 'images/carousel/carousel4.jpg'
    },
    {
        url: 'images/carousel/carousel5.jpg'
    },
    {
        url: 'images/carousel/carousel6.jpg'
    },
    {
        url: 'images/carousel/carousel7.jpg'
    },
    {
        url: 'images/carousel/carousel8.jpg'
    },
    {
        url: 'images/carousel/carousel9.jpg'
    }
];

This is my total images variable, that console logs the number fine:

var totalImages =  carouselImages.length;

Then these are my three divs:

// SET PREVIOUS CAROUSEL IMAGE
$scope.prevImage = {
    'background-image' : 'url(' + carouselImages[totalImages].url + ')'
};

$scope.isPrevActive = false;

// SET CURRENT CAROUSEL IMAGE
$scope.currentImage = {
    'background-image' : 'url(' + carouselImages[0].url + ')'
};

$scope.isCurrentActive = true;

// SET NEXT CAROUSEL IMAGE
$scope.nextImage = {
    'background-image' : 'url(' + carouselImages[1].url + ')'
};

The console says that it 'cannot read url of undefined', but the url is defined in the array. Please help!

1 Answer 1

3

totalImages is out of range. The last index in the array is totalImages - 1:

// SET PREVIOUS CAROUSEL IMAGE
$scope.prevImage = {
    'background-image' : 'url(' + carouselImages[totalImages - 1].url + ')'
};
Sign up to request clarification or add additional context in comments.

1 Comment

School boy error on my part, index doesn't work like nth-child. Thanks!

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.