RangeError
当值不在允许值的集合或范围内时,RangeError 对象指示错误。
¥The RangeError object indicates an error when a value is not in the set or range of allowed values.
描述
¥Description
当尝试将值作为参数传递给不允许包含该值的范围的函数时,会引发 RangeError。
¥A RangeError is thrown when trying to pass a value as an argument to a function that does not allow a range that includes the value.
在以下情况下可能会遇到这种情况:
¥This can be encountered when:
- 将不是允许的字符串值之一的值传递给
String.prototype.normalize(),或者 - 当尝试使用
Array构造函数创建非法长度的数组时,或者 - 将错误值传递给数值方法
Number.prototype.toExponential()、Number.prototype.toFixed()或Number.prototype.toPrecision()时。
RangeError 是 serializable object,因此可以使用 structuredClone() 进行克隆,或者使用 postMessage() 在 工人 之间进行复制。
¥RangeError is a serializable object, so it can be cloned with structuredClone() or copied between Workers using postMessage().
RangeError 是 Error 的子类。
¥RangeError is a subclass of Error.
构造函数
实例属性
¥Instance properties
还从其父级 Error 继承实例属性。
¥Also inherits instance properties from its parent Error.
这些属性在 RangeError.prototype 上定义并由所有 RangeError 实例共享。
¥These properties are defined on RangeError.prototype and shared by all RangeError instances.
RangeError.prototype.constructor-
创建实例对象的构造函数。对于
RangeError实例,初始值为RangeError构造函数。 RangeError.prototype.name-
表示错误类型的名称。对于
RangeError.prototype.name,初始值为"RangeError"。
实例方法
示例
使用 RangeError(对于数值)
使用 RangeError(对于非数字值)
¥Using RangeError (for non-numeric values)
function check(value) {
if (!["apple", "banana", "carrot"].includes(value)) {
throw new RangeError(
'The argument must be an "apple", "banana", or "carrot".',
);
}
}
try {
check("cabbage");
} catch (error) {
if (error instanceof RangeError) {
// Handle the error
}
}
规范
| Specification |
|---|
| ECMAScript Language Specification # sec-native-error-types-used-in-this-standard-rangeerror |
浏览器兼容性
BCD tables only load in the browser