As described by @basilikum, this is because .slice() is required to use .slice() . To understand why this is required, imagine that you wrote your own version of Array.prototype.slice() after reading the MDN docs:
Syntax
Array.slice(begin[, end])
Options
begin
Zero based index to start extraction.
As a negative index, begin indicates the offset from the end of the sequence. slice(-2) extracts the second-last element and the last element in the sequence.
end
Zero based index to complete extraction. slice extracts to, but not including end .
slice(1,4) retrieves the second item through the fourth item (items indexed 1, 2, and 3).
As a negative index, end indicates the offset from the end of the sequence. slice(2,-1) retrieves the third element through the second-last element in the sequence.
If end omitted, slice fetches to the end of the sequence.
To deal with all of these cases and a few others that are not listed, your code should be something like these lines (this may have errors, but it should be close):
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 < 0 ) begin = length + begin; // But make sure that didn't put it less than 0 if( begin < 0 ) begin = 0; // Handle missing end or end too long if( end === undefined || end > length ) end = length; // Handle negative end (don't have to worry about < 0) if( end < 0 ) end = length + end; // Now copy the elements and return resulting array var result = []; for( var i = begin; i < end; ++i ) result.push( this[i] ); return result; };
This is why .slice() requires this.length - you cannot write a function without it.
Michael geary
source share