0

我正在查找数组值以来回导航滑块,并且在我的逻辑中遇到了关于未定义值的漏洞。就目前而言,我在数组中查找当前幻灯片,添加或减去数组中的位置,如果该值存在,则更新位置。但是,如果数组中的值不存在(即数组中有 3 个对象并且滑块试图查找#4),它会引发类型错误。

需要一种更好的方式来表达“如果存在价值,则更新)。看起来很简单,但我还没有想到一个好的解决方案。

我想我可以很容易地摆脱这个update变量,但我认为最好在数组中查找一次值并将其保存以用于 body 类更新,知道我的意思吗?

请参阅下面的代码,谢谢!

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;
    }
}
4

2 回答 2

1

试试下面的。

update = $slides[next] ? $slides[next].slide : false;
于 2013-01-16T20:23:26.847 回答
1

您应该检查边界。

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;
}
于 2013-01-16T20:25:10.643 回答