0

I'm looking up array values to navigate a slider back and forth and have come accross a hole in my logic regarding undefined values. As it stands, I look up the current slide within the array, add or subtract from the position in the array, and if that value exists update the position. It works, however, if the value within the array doesnt exist (i.e. there are 3 objects in the array and the sliders trying to look up #4) it throws a type error.

Need a better way of saying "if value exists, then update). Seems pretty simple but I havn't thought of a good solution.

I suppose I can easily get rid of the update variable, but I think it's good to look up the value in the array once and save it for use in the body class update, know what I mean?

See code below and thank you!

function slide(direction){

/* Get Current */

    var current = $bod.attr('class'),
        next,
        update;

/* Navigate */

    if (direction === 'right'){

        next = $current + 1;

    } else if (direction === 'left'){

        next = $current - 1;

    } else if (direction === 'home'){

        next = $home;
    }

/* Update */

    // Issue is here. If the next slide is undefined, everything crashes

    update = $slides[next].slide;

    // Was trying to address the issue with this line:

    if (update){

        $bod.removeClass(current).addClass(update);

        $current = next;
    }
}
0

2 Answers 2

1

Try the following.

update = $slides[next] ? $slides[next].slide : false;
Sign up to request clarification or add additional context in comments.

2 Comments

perfectly simple, thank you. i've never used the ? operator; mind explaining?
@technopeasant It's called conditional operator. developer.mozilla.org/en-US/docs/JavaScript/Guide/…
1

You should check for bounds instead.

if ((direction === 'right') && ($current < $slides.length - 1)){
  next = $current + 1;
} else if ((direction === 'left') && ($current > 0)){
  next = $current - 1;
} else if (direction === 'home'){
  next = $home;
}

Comments

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.