我试图理解String.prototype.repeat()-polyfill的代码。
此处的完整代码:https : //developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/String/repeat
我问自己以下部分是否合乎逻辑:
// Tries to cast the parameter 'count' to a number.
count = +count;
// If the cast fails ('count' has become NaN) then
// assign 0 to the parameter-variable.
if (count != count) {
count = 0;
}
// Does some more checks with the parameter ...
if (count < 0) {
throw new RangeError('repeat count must be non-negative');
}
if (count == Infinity) {
throw new RangeError('repeat count must be less than infinity');
}
// End of checks ...
// Rounds the parameter to next lower integer.
count = Math.floor(count);
// Checks if count is 0. In that case: Terminate
// the function / Return an empty string.
if (str.length == 0 || count == 0) {
return '';
}
为什么不在投射失败后终止(在顶部)?
而是分配0,然后运行检查,并检查0。如果该状态为true,则终止。
对我来说毫无意义。
有什么我不了解的吗?
因为此polyfill需要实现与规范中相同的行为。规范说如果值小于零,则应该引发错误。
另外,在开始时强制转换为数字是可以的,但是可以使用无效数字直接调用此函数,如下所示:
var string = 'abc';
string.repeat(-1); // throws range error
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句