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

时间:2015-02-07 23:57:52

标签: javascript arrays iteration underscore.js

我有一个数组

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

我需要一个函数,它根据给定的键值返回下一个或前一个数组键:

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

所以要找到4的下一个,我调用该函数; closestTo(arr, 4, 'next' )这应该返回1

closestTo(arr, 4, 'prev' )应该返回2

使用underscore可以实现这方面的任何想法吗?

3 个答案:

答案 0 :(得分:4)

也许有些事情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];
}

答案 1 :(得分:3)

我为你写了脚本:) 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' ));

答案 2 :(得分:1)

您只需要纯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];
}