我正在查找数组值来浏览滑块来回,并已在我的逻辑中关于未定义的值穿过一个洞。就目前而言,我查找数组中的当前幻灯片,从数组中的位置加或减,如果该值存在,则更新位置。但是,如果数组中的值不存在(即数组中有3个对象,并且滑块试图查找#4),它会起作用,它会引发类型错误。jQuery处理未定义的数组值
需要说“如果值存在,然后更新)一个更好的方式。似乎很简单,但我没有带一个很好的解决方案的想法。
我想我可以很容易地摆脱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;
}
}
非常简单,谢谢。我从来没有用过?操作;介意解释? – technopeasant
@technopeasant它被称为条件运算符。 https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Expressions_and_Operators#conditional_operator –