Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>using modulus this is pretty easy:</p> <pre><code>var array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], index = 8, n = 3; var result = []; for (var i = index - n, len = array.length; i &lt;= index + n; i++) { result.push(array[(i + len) % len]); } console.log(result); </code></pre> <p>Edit JSFiddle: <a href="http://jsfiddle.net/cmymS/" rel="nofollow">http://jsfiddle.net/cmymS/</a></p> <p>An explanation for the modulo operator in this example:</p> <p>The modulo operator handles going over the boundaries. Inside of the for loop, <code>i</code> is a 'virtual' index in the array that can be less than 0 or <code>&gt;= len</code>. You can think of this as having infinite repetitions of your array both on the left and right of your actual array. If <code>i &lt; 0</code>, we are accessing one of the virtual arrays to the left, if <code>i &gt;= len</code>, we're accessing one of the virtual arrays to the right. The index transformation <code>(i + len) % len</code> then handles translating 'virtual' indices back into actual array indices.</p> <p>There are two boundary conditions and the case of accessing a 'normal' index:</p> <p>a) <code>i &lt; 0</code>: Consider e.g. <code>i = -3</code>.</p> <p><code>(i + len)</code> will shift the position by one whole array so that we're working in the virtual array to the right, but pointing at the same element. The modulus has no effect since <code>len - 3</code> is smaller than <code>len</code>.</p> <p>b) <code>i &gt;= len</code>: Consider e.g. <code>i = len + 4</code></p> <p><code>(i + len)</code> will shift the position one array to the right. In our example, <code>(i + len)</code> will be <code>(len + 4 + len)</code> but the modulo neutralizes those shifts so we get <code>4</code>.</p> <p>c) <code>i</code> is a valid index in the original array <code>(i + len)</code> will shift the position one array to the right, but this is reset by the modulus since <code>0 &lt;= i &lt; len</code>. <code>(i + len) % len = i</code>.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload