Using the Javascript slice() method with no arguments

前端 未结 1 1621
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 16:07

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 passi

相关标签:
1条回答
  • 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.

    0 讨论(0)
提交回复
热议问题