Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

jquery - get prev and next items in array

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...