获取数组中的上一个和下一个项目 [英] get prev and next items in array

查看:96
本文介绍了获取数组中的上一个和下一个项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数字数组

var projects = [ 645,629,648 ];

和数字645

我需要获取下一个(629)和上一个(648)数字吗?

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

我可以用jquery吗?

can i do it with jquery?

推荐答案

您可以使用jquery的

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

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

或者,基于功能:

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

这篇关于获取数组中的上一个和下一个项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆