i have an array of numbers
var projects 开发者_JAVA技巧= [ 645,629,648 ];
and a number 645
i need to get the next(629) and prev(648) numbers?
can i do it with 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];
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];
}
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):
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.
You only need to sort the array once afterwards you can just use the code starting from //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]);
精彩评论