使用不带参数的 Javascript slice() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11286950/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Using the Javascript slice() method with no arguments
提问by user886596
I'm currently reading through this jquery masking pluginto 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.
我目前正在通读这个jquery 屏蔽插件以尝试了解它是如何工作的,并且在许多地方作者调用了slice()
不传递任何参数的函数。例如,这里的_buffer
变量是slice()
d,_buffer.slice()
并且_buffer
似乎拥有相同的值。
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();
}
}
回答by nnnnnn
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:
该.slice()
方法制作数组的(浅)副本,并采用参数来指示要复制源数组的哪个子集。不带参数调用它只会复制整个数组。那是:
_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 startindex. 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
.
编辑:开始索引不是强制性的吗?是的。和不。有点。JavaScript 引用(如MDN)通常说.slice()
至少需要一个参数,即起始索引。.slice()
没有参数的调用就像在说.slice(undefined)
。在ECMAScript Language Spec 中,.slice()
算法的第 5 步说“Let relativeStart
be ToInteger(start)
”。如果您查看抽象操作的算法ToInteger()
,后者又使用ToNumber()
,您会看到它最终转换undefined
为0
。
Still, in my own code I would always say .slice(0)
, not .slice()
- to me it seems neater.
尽管如此,在我自己的代码中,我总是会说.slice(0)
,不是.slice()
- 对我来说似乎更整洁。