考虑以下代码:
(function () {
'use strict';
delete document.body.dataset.state;
})();
其中 body dataset
是空的。 Safari 将所有 DOMStringMap 值——好吧,我猜是——作为 ReadOnly
,以及它们的 enumerable
、configurable
和 writable
描述符值都设置为 false
。这会导致 TypeError: Unable to delete property
出现在上述示例中。
但在 Chrome 数据集中,属性描述符值设置为 true
(可以使用 Object.getOwnPropertyDescriptor()
检查),并且删除不存在的属性不会引发错误。
那么,什么样的行为是正确的呢?规范说明了 readonly dataset , 但是 writable DOMStringMap ,所以我假设数据集属性必须是可删除的。我错过了什么吗?
最佳答案
可能是严格模式的缘故
Third, strict mode makes attempts to delete undeletable properties throw (where before the attempt would simply have no effect):
'use strict';
delete Object.prototype; // throws a TypeError
您可能想看看 this documentation
你也可以尝试将对象值设置为未定义,它有点毛茸茸但有效..
关于javascript - 尝试在严格模式下删除数据集属性时,Safari 上的“无法删除属性”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28973603/