如何在使用严格模式时从JavaScript对象中删除属性 [英] How to remove a property from a JavaScript object when using Strict Mode
问题描述
阅读此问题:如何删除一个JavaScript对象?
但是我的代码在全局声明中使用'use strict';
它存在于整个文件中。
However my code uses 'use strict';
in global declaration which means it is present in the whole file.
删除
语句在严格模式下被禁止(无效)。 文档
delete
statement is forbidden in strict mode (has no effect). Documentation
如何在使用严格模式时从对象中删除属性而不必求助于克隆和循环属性,跳过要删除的属性?
How can one delete properties from objects when using strict mode without having to resort to cloning and looping over properties, skipping the one that is to be deleted?
更新和澄清:
我需要在将对象发送到服务器之前从对象中删除该属性,该服务器会抱怨未知属性。
I need to delete a property from an object before sending it to the server, which complains for unknown properties.
推荐答案
删除
不禁止进入严格模式。
delete
is not forbidden in strict mode.
-
在严格模式下删除不可删除的属性会引发错误。在非严格模式下,它会无声地失败。无论哪种方式,除了克隆对象外都不可能。
Deleting un-deletable properties in strict mode throws an error. In non-strict mode it fails silently. Either way, it's not possible except for cloning the object.
你无法删除普通名称;抛出语法错误。如果变量是一个全局变量,你可以像这样绕过它;
You can't delete plain names; a syntax error is thrown. If the variable is a global variable, you can get around it like so;
// Imagine we're global here.
var foo = 4;
delete foo; // syntax error
delete window.foo; // works.
这篇关于如何在使用严格模式时从JavaScript对象中删除属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!