【发布时间】:2013-01-16 20:18:53
【问题描述】:
我正在查找数组值来来回导航滑块,并且在我的逻辑中遇到了关于未定义值的漏洞。就目前而言,我在数组中查找当前幻灯片,添加或减去数组中的位置,如果该值存在,则更新位置。但是,如果数组中的值不存在(即数组中有 3 个对象并且滑块试图查找 #4),它会引发类型错误。
需要一种更好的方式来表达“如果值存在,则更新”。看起来很简单,但我没有想到一个好的解决方案。
我想我可以轻松摆脱update 变量,但我认为最好在数组中查找一次值并将其保存以用于主体类更新,知道我的意思吗?
查看下面的代码,谢谢!
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;
}
}
【问题讨论】:
标签: jquery arrays class variables undefined