jQuery 获取数组中的上一个和下一个项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2498415/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 13:38:03  来源:igfitidea点击:

get prev and next items in array

jquery

提问by eyalb

i have an array of numbers

我有一组数字

var projects = [ 645,629,648 ];

and a number 645

和一个数字 645

i need to get the next(629) and prev(648) numbers?

我需要得到下一个(629)和上一个(648)数字?

can i do it with jquery?

我可以用 jquery 做吗?

回答by Nick Craver

You can make it a bit shorter overall using jquery's $.inArray()methodwith a modulus:

您可以使用带有模数的jquery$.inArray()方法使其整体更短:

var p = [ 645,629,648 ];
var start = 645;
var next = p[($.inArray(start, p) + 1) % p.length];
var prev = p[($.inArray(start, p) - 1 + p.length) % p.length];

Or, function based:

或者,基于函数:

function nextProject(num) { 
  return p[($.inArray(num, p) + 1) % p.length]; 
}
function prevProject(num) { 
  return p[($.inArray(num, p) - 1 + p.length) % p.length];
}

回答by Veger

I do not know about jQuery, but it is fairly simple to create something on your own (assuming that you have always unique numbers in your array):

我不知道 jQuery,但自己创建一些东西是相当简单的(假设你的数组中总是有唯一的数字):

var projects = [ 645,629,648 ];

function next(number)
{
    var index = projects.indexOf(number);
    index++;
    if(index >= projects.length)
        index = 0;

    return projects[index];
}

Calling next()with a project number returns the next project number. Something very similar can be made for the prev()function.

next()使用项目编号调用将返回下一个项目编号。可以为该prev()功能制作一些非常相似的东西。

回答by jitter

You only need to sort the array once afterwards you can just use the code starting from //start

您只需要在之后对数组进行一次排序就可以使用从 //start

If number is not present nothing is output

如果数字不存在,则不输出任何内容

var projects = [ 645, 629, 648 ], number = 645, i = -1;
projects.sort(function(a, b) {
    return a > b ? 1 : -1;
});
//start
i = projects.indexOf(number);
if(i > 0)
    alert(projects[i-1]);
if(i < (projects.length - 1) && i >= 0)
    alert(projects[i+1]);