使用mod环绕 [英] Using mod to wrap around

查看:57
本文介绍了使用mod环绕的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设数组的长度为1000.我正在尝试创建一种简单的方法来遍历存储在数组中的图像路径,而不会超出范围。当点击下一步按钮来增加数组索引时,下面的方法可以很好地处理使用模数的回绕,但是当我不得不从索引中减去并减去一个时(当用户点击上一个按钮时)。

Assume the array has a length of 1000. I am trying to create a simple way to traverse the image paths stored in the array without going out of bounds. The method below handles the wrap around using modulus well when it comes to clicking the 'next' button to increment array index, but not when I have to decrement and deduct one from the index (when the user clicks the previous button).

基本上我要做的是:

998 -> click next -> 999
999 -> click next -> 0
0 -> click previous -> 999

我的Javacript

My Javacript

var index = 0;

$('.catalog-img-container').attr("src", javascript_array[index]);
$(".next").click(function(){
        $('.catalog-img-container').attr("src", javascript_array[++index%arrayLength]);
    });         
$(".previous").click(function(){
    $('.catalog-img-container').attr("src", javascript_array[--index]);
    alert(index);

我感谢任何帮助

许多人提前感谢。

推荐答案

这可能会有更优雅的方式,但这很简单:

There might be a more elegant way around this, but this is simple:

$(".previous").click(function(){
    if (--index < 0) index = arrayLength - 1;
    $('.catalog-img-container').attr("src", javascript_array[index%arrayLength]);
}); 

这篇关于使用mod环绕的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆