在js数组中查找下一个和上一个键

Find next and previous keys in js array

我有一个数组

var arr = ["1", "3", "2", "4"];

我需要一个函数,它 return 根据给定键值设置下一个或上一个数组键:

function closestTo(arr, key, direction) { 
 // do stuff here and return the next or previous id
}

为了找到 4 中的下一个,我调用了函数; closestTo(arr, 4, 'next' ) 这应该 return 1

closestTo(arr, 4, 'prev' )应该return2

这方面的任何想法也可以通过 underscore 实现吗?

也许like this

function closestTo(arr, key, direction) {
    var offset_index = (direction === 'prev') ? -1 : 1;

    // Convert to integers
    var intarr = arr.map(function(x) {
        return parseInt(x, 10);
    });

    return intarr[(intarr.length + intarr.indexOf(key) + offset_index) % intarr.length];
}

你只需要纯 JavaScript 即可:

function closestTo(arr, key, direction) {
    var keyIndex = arr.indexOf(key),
        indexToReturn;

    if (direction === 'prev') {
        indexToReturn = keyIndex > 0 ? keyIndex - 1 : arr.length -1;
    } else if (direction === 'next') {
        indexToReturn = keyIndex < arr.length - 1 ? keyIndex + 1 : 0;
    }

    return arr[indexToReturn];
}

我已经为你写好了脚本:)
http://jsfiddle.net/maxim_mazurok/6s7z6zwt/
但是如果你想用数字作为第二个参数调用函数,数组应该像 var arr = [1, 2, 3, 4];

var arr = [1, 2, 3, 4];

function closestTo(arr, key, direction) {
    var last = arr.length - 1;
    var first = 0;
    var keyIndex = arr.indexOf(key);
    switch (direction) {
        case ('next'):
            if (keyIndex != last) {
                return arr[keyIndex + 1];
            } else {
                return arr[first];
            }
            break;
        case ('prev'):
            if (keyIndex != first) {
                return arr[keyIndex - 1];
            } else {
                return arr[last];
            }
    }
}
alert(closestTo(arr, 4, 'next' ));
alert(closestTo(arr, 4, 'prev' ));