RangeError: repeat count must be non-negative

String.prototype.repeat() 方法的 count 引數為負數時,JavaScript 會丟擲“重複計數必須為非負數”的異常。

訊息

RangeError: Invalid count value: -1 (V8-based)
RangeError: repeat count must be non-negative (Firefox)
RangeError: String.prototype.repeat argument must be greater than or equal to 0 and not be Infinity (Safari)

錯誤型別

RangeError

哪裡出錯了?

已使用 String.prototype.repeat() 方法。它有一個 count 引數,表示字串重複的次數。它必須介於 0 和正 Infinity 之間(不包括正無窮),並且不能是負數。允許值的範圍可以描述為:[0, +∞)。

示例

無效案例

js
"abc".repeat(-1); // RangeError

有效情況

js
"abc".repeat(0); // ''
"abc".repeat(1); // 'abc'
"abc".repeat(2); // 'abcabc'
"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer)

另見