If you have an array, for example, of five elements, the middle element is at index two:
var arr = [ item, item, middle, item, item];
Dividing the length into two and using Math.round will give you an index of three, not two, so you first need to subtract one from the length:
var middle = arr[Math.round((arr.length - 1) / 2)];
In your question, you say that you should use Math.round , but if this is not a requirement, you can get the same result using Math.floor :
var middle = arr[Math.floor(arr.length / 2)];
For an array with an even number of elements, this will give you the second of two elements that are in the middle. If you want first instead, use Math.floor and subtract one from the length. This still gives the same result for an odd number of elements:
var middle = arr[Math.floor((arr.length - 1) / 2)];
Guffa
source share