【问题标题】:jQuery handling undefined array valuejQuery处理未定义的数组值
【发布时间】: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


    【解决方案1】:

    试试下面的。

    update = $slides[next] ? $slides[next].slide : false;
    

    【讨论】:

    【解决方案2】:

    您应该改为检查边界。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2017-07-07
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多