i have an array of numbers
var projects = [ 645,629,648 ];
and a number 645
i need to get the next(629) and prev(648) numbers?
can i do it with jquery?
The next() function moves the internal pointer to, and outputs, the next element in the array. Related methods: prev() - moves the internal pointer to, and outputs, the previous element in the array. current() - returns the value of the current element in an array.
The PHP next( ) function is used to advance the internal array pointer. It advances the internal array pointer one place forward before returning the element value. This function was introduced in PHP 4.0.
If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .
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]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With