使用没有参数的Javascript slice()方法 [英] Using the Javascript slice() method with no arguments

查看:1418
本文介绍了使用没有参数的Javascript slice()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读这个 jquery masking插件,试图了解它是如何工作的,并且在很多地方作者调用 slice()函数,不传递任何参数。例如, _buffer 变量是 slice() d,以及 _buffer.slice() _buffer 似乎保持相同的值。

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


推荐答案

.slice()方法生成数组的(浅)副本,并获取参数以指示要复制的源数组的哪个子集。不带参数调用它只会复制整个数组。那就是:

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

编辑:启动索引是否必须?是。和不。有点。 JavaScript引用(例如 MDN )通常会说 .slice()至少需要一个参数 start 索引。不带参数调用 .slice()就像说 .slice(undefined)。在 ECMAScript语言规范中,第5步 .slice()算法说让 relativeStart ToInteger(开始)。如果你看一下抽象操作的算法,请 ToInteger() ,后者又使用 ToNumber() ,您会看到它最终将 undefined 转换为 0

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.

仍然,在我自己的代码中,我总是说 .slice(0),而不是 .slice() - 对我而言似乎更整洁。

Still, in my own code I would always say .slice(0), not .slice() - to me it seems neater.

这篇关于使用没有参数的Javascript slice()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆