在 JavaScript 中,如果“删除”一个不存在的属性会发生什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16406784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In JavaScript, what happens if "delete" a property that doesn't exist?
提问by thisissami
What happens in JavaScript if I have a variable, say:
如果我有一个变量,JavaScript 会发生什么,比如:
var exampleObject = {one:'foo',two:'bar'};
and then I delete a property that doesn't exist, a la:
然后我删除了一个不存在的属性,a la:
delete exampleObject.seven;
Is there a standard course of action that takes place everywhere (nothing, error message, script crashes, etc.), or is this dependent on some kind of implementation (browser engine, etc.)?
是否存在随处可见的标准操作过程(无、错误消息、脚本崩溃等),或者这是否依赖于某种实现(浏览器引擎等)?
采纳答案by user2246674
Nothing happens.
没发生什么事。
Assuming, x = {}
, Type(x.y)
is nota Reference Specifcation Type(there cannot be a "reference" to a property that does not exist). According to 11.4.1 The delete Operator, this satisfies the rule:
假设,x = {}
,Type(x.y)
是不是一个参考Specifcation类型(不可能有一个“参考”来表示不存在的属性)。根据11.4.1 删除操作符,这满足规则:
- Let ref be the result of evaluating UnaryExpression.
- If Type(ref) is not Reference, return true.
- ...
- 让 ref 为计算 UnaryExpression 的结果。
- 如果 Type(ref) 不是 Reference,则返回 true。
- ...
This behavior (of "no action") has existed for a long time - any environment that behaves differently is non-compliant. From the 3rd Edition ECMAScript Specification:
这种行为(“无行动”)已经存在很长时间了——任何行为不同的环境都是不合规的。从第三版 ECMAScript 规范:
When the [[Delete]] method of O is called with property name P, the following steps are taken:
- If O doesn't have a property with name P, return true.
- ..
当使用属性名P调用O的[[Delete]]方法时,采取如下步骤:
- 如果 O 没有名为 P 的属性,则返回 true。
- ..
回答by kennebec
If exampleObject is an object, the return value from delete is true, even if the property does not exist.
如果 exampleObject 是一个对象,则 delete 的返回值为true,即使该属性不存在。