为什么减(负)值与索引一起使用?

Ale*_*nik -1 javascript jquery

我是jquery的新手,基本上,我决定将Jquery用于实际用途,所以我构建了以下脚本:

$(function () {
    $(document).on('keydown', checkey);

    var index = 0,
        $items = $('ul li a');


    function checkey(e) {

        // console.log($items);    

        if (e.which == 38) {
            // key up
            index -= 1;
        };
        if (e.which == 40) {
            //key down
            index += 1;
        }

        console.log(index);

        $items.eq(index).trigger('focus');
    }


}); 
Run Code Online (Sandbox Code Playgroud)

使用此脚本,您可以使用向上和向下箭头键导航菜单.

小提琴在这里.现在我有一个关于我使用的代码的问题,特别是下面的代码行:

$items.eq(index).trigger('focus');
Run Code Online (Sandbox Code Playgroud)

现在,索引变量在我的脚本中递增和递减,但是当我继续按下键盘,并且索引继续递减并且低于0 IE -1,-2,-3,-4 ...等时$items.eq(index).trigger('focus');,此行仍然工作,我不希望它与负值一起工作,我期待它只能在0-4工作.

那么负值如何以及为何与以下陈述一起使用:

eg. $items.eq(-2).trigger('focus'); ??
Run Code Online (Sandbox Code Playgroud)

注意:在小提琴中,请检查控制台并向上和箭头向下试验,以了解我在说什么.

Kri*_*ris 5

jQuery API文档:

提供负数表示从集合结束开始的位置,而不是开头.