Wednesday, June 5, 2024
 Popular · Latest · Hot · Upcoming
136
rated 0 times [  138] [ 2]  / answers: 1 / hits: 32825  / 12 Years ago, mon, july 2, 2012, 12:00:00

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();
}
}

More From » jquery

 Answers
8

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.


[#84536] Friday, June 29, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
sabrina

Total Points: 92
Total Questions: 92
Total Answers: 85

Location: Palestine
Member since Thu, Feb 2, 2023
1 Year ago
;