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();
}
}
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: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 “LetrelativeStartbeToInteger(start)“. If you look at the algorithm for the abstract operationToInteger(), which in turn usesToNumber(), you’ll see that it ends up convertingundefinedto0.Still, in my own code I would always say
.slice(0), not.slice()– to me it seems neater.