类型错误:无法删除不可配置的数组元素

当尝试对数组进行 缩短长度,但数组的元素之一是 non-configurable 时,会发生 JavaScript 异常 "无法删除不可配置的数组元素"。

¥The JavaScript exception "can't delete non-configurable array element" occurs when it was attempted to shorten the length of an array, but one of the array's elements is non-configurable.

信息

¥Message

TypeError: Cannot delete property '1' of [object Array] (V8-based)
TypeError: can't delete non-configurable array element (Firefox)
TypeError: Unable to delete property. (Safari)

错误类型

¥Error type

TypeError

什么地方出了错?

¥What went wrong?

尝试对数组进行 缩短长度,但数组的元素之一是 non-configurable。当缩短数组时,超出新数组长度的元素将被删除,这种情况会失败。

¥It was attempted to shorten the length of an array, but one of the array's elements is non-configurable. When shortening an array, the elements beyond the new array length will be deleted, which failed in this situation.

configurable 属性控制是否可以从对象中删除该属性以及是否可以更改其属性(writable 除外)。

¥The configurable attribute controls whether the property can be deleted from the object and whether its attributes (other than writable) can be changed.

通常,数组初始值设定项 创建的对象中的属性是可配置的。但是,例如,当使用 Object.defineProperty() 时,默认情况下该属性不可配置。

¥Usually, properties in an object created by an array initializer are configurable. However, for example, when using Object.defineProperty(), the property isn't configurable by default.

示例

¥Examples

由 Object.defineProperty 创建的不可配置属性

¥Non-configurable properties created by Object.defineProperty

如果你未将它们指定为可配置,则 Object.defineProperty() 默认情况下会创建不可配置的属性。

¥The Object.defineProperty() creates non-configurable properties by default if you haven't specified them as configurable.

js
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0 });
Object.defineProperty(arr, 1, { value: "1" });

arr.length = 1;
// TypeError: can't delete non-configurable array element

如果你打算缩短数组,则需要将元素设置为可配置。

¥You will need to set the elements as configurable, if you intend to shorten the array.

js
"use strict";
const arr = [];
Object.defineProperty(arr, 0, { value: 0, configurable: true });
Object.defineProperty(arr, 1, { value: "1", configurable: true });

arr.length = 1;

密封数组

¥Sealed Arrays

Object.seal() 函数将所有现有元素标记为不可配置。

¥The Object.seal() function marks all existing elements as non-configurable.

js
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);

arr.length = 1;
// TypeError: can't delete non-configurable array element

你需要删除 Object.seal() 调用,或者复制它。对于副本,缩短数组的副本不会修改原始数组的长度。

¥You either need to remove the Object.seal() call, or make a copy of it. In case of a copy, shortening the copy of the array does not modify the original array length.

js
"use strict";
const arr = [1, 2, 3];
Object.seal(arr);

// Copy the initial array to shorten the copy
const copy = Array.from(arr);
copy.length = 1;
// arr.length === 3

也可以看看