I'm currently reading through this jquery masking plugin to try and understand how it works, and in numerous places the author calls the slice()
function passing no arguments to it. For instance here the _buffer
variable is slice()
d, and _buffer.slice()
and _buffer
seem to hold the same values.
Is there any reason for doing this, or is the author just making the code more complicated than it should be?
//functionality fn function unmaskedvalue($input, skipDatepickerCheck) { var input = $input[0]; if (tests && (skipDatepickerCheck === true || !$input.hasClass('hasDatepicker'))) { var buffer = _buffer.slice(); checkVal(input, buffer); return $.map(buffer, function(element, index) { return isMask(index) && element != getBufferElement(_buffer.slice(), index) ? element : null; }).join(''); } else { return input._valueGet(); } }
JavaScript Array slice()The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end. The slice() method does not change the original array.
All you know that arguments is a special object that holds all the arguments passed to the function. And as long as it is not an array - you cannot use something like arguments. slice(1) .
The slice() method does not change the original string. The start and end parameters specifies the part of the string to extract. The first position is 0, the second is 1, ... A negative number selects from the end of the string.
The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn't change the original array. The splice( ) method changes an array, by adding or removing elements from it.
The .slice()
method makes a (shallow) copy of an array, and takes parameters to indicate which subset of the source array to copy. Calling it with no arguments just copies the entire array. That is:
_buffer.slice(); // is equivalent to _buffer.slice(0); // also equivalent to _buffer.slice(0, _buffer.length);
EDIT: Isn't the start index mandatory? Yes. And no. Sort of. JavaScript references (like MDN) usually say that .slice()
requires at least one argument, the start index. Calling .slice()
with no arguments is like saying .slice(undefined)
. In the ECMAScript Language Spec, step 5 in the .slice()
algorithm says "Let relativeStart
be ToInteger(start)
". If you look at the algorithm for the abstract operation ToInteger()
, which in turn uses ToNumber()
, you'll see that it ends up converting undefined
to 0
.
Still, in my own code I would always say .slice(0)
, not .slice()
- to me it seems neater.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With