Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>As @basilikum described, this is because <code>.length</code> is required in order to use <code>.slice()</code>. To understand <em>why</em> it's required, imagine that you were writing your own version of <code>Array.prototype.slice()</code> after reading the MDN docs:</p> <hr> <h3>Syntax</h3> <pre><code>Array.slice(begin[, end]) </code></pre> <h3>Parameters</h3> <p><strong><code>begin</code></strong></p> <p>Zero-based index at which to begin extraction.</p> <p>As a negative index, <code>begin</code> indicates an offset from the end of the sequence. <code>slice(-2)</code> extracts the second-to-last element and the last element in the sequence.</p> <p><strong><code>end</code></strong></p> <p>Zero-based index at which to end extraction. <code>slice</code> extracts up to but not including <code>end</code>.</p> <p><code>slice(1,4)</code> extracts the second element through the fourth element (elements indexed 1, 2, and 3).</p> <p>As a negative index, <code>end</code> indicates an offset from the end of the sequence. <code>slice(2,-1)</code> extracts the third element through the second-to-last element in the sequence.</p> <p>If <code>end</code> is omitted, <code>slice</code> extracts to the end of the sequence.</p> <hr> <p>To handle all those cases and a few more not listed, your code would have to be something along these lines (this may have bugs but should be close):</p> <pre><code>Array.prototype.myslice = function( begin, end ) { // Use array length or 0 if missing var length = this.length || 0; // Handle missing begin if( begin === undefined ) begin = 0; // Handle negative begin, offset from array length if( begin &lt; 0 ) begin = length + begin; // But make sure that didn't put it less than 0 if( begin &lt; 0 ) begin = 0; // Handle missing end or end too long if( end === undefined || end &gt; length ) end = length; // Handle negative end (don't have to worry about &lt; 0) if( end &lt; 0 ) end = length + end; // Now copy the elements and return resulting array var result = []; for( var i = begin; i &lt; end; ++i ) result.push( this[i] ); return result; }; </code></pre> <p>That's why <code>.slice()</code> requires <code>this.length</code>&mdash;you wouldn't be able to write the function without it.</p>
 

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