TypeError: can't delete non-configurable array element - 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: can't delete non-configurable array element (Firefox)
TypeError: Cannot delete property '2' of [object Array] (Chrome)

Error type

TypeError

What went wrong?

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.

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

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

Non-configurable properties created by Object.defineProperty

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

var 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.

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

arr.length = 1;

Seal-ed Arrays

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

var arr = [1,2,3];
Object.seal(arr);

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

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.

var arr = [1,2,3];
Object.seal(arr);

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

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:105 次

字数:4625

最后编辑:7 年前

编辑次数:0 次

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文