为什么即使没有从对象中删除属性,删除操作符也返回true [英] Why delete operator returns true even if property wasn't deleted from an object

查看:50
本文介绍了为什么即使没有从对象中删除属性,删除操作符也返回true的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

>>> var par = {a: 1, b: 2};
undefined
>>> var ch = Object.create(par);
undefined
>>> delete ch.a
true
>>> ch
Object { a=1, b=2}

推荐答案

您误解了删除操作返回的内容:

You misunderstood what delete returns:

如果该属性是自己的不可配置属性,则以严格模式抛出(在非严格条件下返回false).在所有其他情况下返回true. ( https://developer.mozilla.org/zh- US/docs/Web/JavaScript/Reference/Operators/delete )

delete ch.a试图在ch中找到属性a,失败(由于ch没有这样的 own 属性),什么也不做,很高兴地返回了true.如果您写了delete ch.foobar,结果将是相同的.但是,如果您尝试使用不可配置的属性(例如delete ch.__proto__),则结果将为false.

delete ch.a tries to locate the property a in ch, fails (since ch doesn't have such own property), does nothing and happily returns true. If you wrote delete ch.foobar, the result would be the same. If however, you tried a non-configurable property (e.g. delete ch.__proto__), the result would be false.

这篇关于为什么即使没有从对象中删除属性,删除操作符也返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆