JavaScript repeat Polyfill:这些代码结构有意义吗?

JavaScript repeat Polyfill:这些代码结构有意义吗?,javascript,algorithm,Javascript,Algorithm,我试图理解String.prototype.repeat()-polyfill的代码 请在此完成代码: 我问自己以下部分是否合乎逻辑: // 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

我试图理解String.prototype.repeat()-polyfill的代码

请在此完成代码:

我问自己以下部分是否合乎逻辑:

    // 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 '';
    }
//尝试将参数“count”强制转换为数字。
计数=+计数;
//如果强制转换失败(“计数”变为NaN),则
//将0指定给参数变量。
如果(计数!=计数){
计数=0;
}
//对参数执行更多检查。。。
如果(计数<0){
抛出新的RangeError('重复计数必须为非负');
}
如果(计数==无穷大){
抛出新的RangeError('重复计数必须小于无穷大');
}
//检查结束。。。
//将参数舍入到下一个较低的整数。
计数=数学地板(计数);
//检查计数是否为0。在这种情况下:终止
//函数/返回一个空字符串。
如果(str.length==0 | | count==0){
返回“”;
}
为什么不在强制转换失败后终止(在顶部)

而不是分配0,运行检查,检查0。如果该状态为真,则终止

对我来说毫无意义


有什么我不明白的吗?

因为此polyfill需要实现与规范中相同的行为。说明:若值小于零,则应抛出错误

此外,在开始时强制转换为数字也可以,但可以使用无效数字直接调用此函数,如下所示:

var string = 'abc';
string.repeat(-1); // throws range error

将计数设置为数字,如果失败,将其设置为0,如果小于0,则抛出范围错误。。。我看不出有什么问题。。。0不是一个范围错误,它是一个有效值。我想第二次使用“count==0”检查应该检查是否有类似于0.49的值被指定为参数。由于Math.floor(),该值将变为0。但这仍然不能解释为什么函数在第一次检查后没有终止…?:|奇怪…是的,我想你可以返回“”而不是设置count=0。。再看一眼,我现在明白你是从哪里来的了