简体   繁体   English

Javascript删除运算符

[英]Javascript delete operator

I read a book about javascript that said: 我读了一本关于javascript的书说:

var o = {x:1 , y:2 };
delete o ; // Can't delete a declared variable so returns false;

However, the book also states that the variables declared outside any function scope are properties of the global object. 但是,本书还指出在任何函数范围之外声明的变量是全局对象的属性。

Why aren't we allowed to delete it then if it is a property of the global object? 如果它是全局对象的属性,为什么我们不允许删除它呢?

By saying: 说:

var o = {x:1 , y:2 };

in the top level scope, you are declaring a global variable , which can not be deleted. 在顶级作用域中,您要声明一个无法删除的全局变量 It does create a property on the global object (which is aliased to the window object in browsers), but it is a special property indeed. 它确实在全局对象上创建了一个属性(在浏览器中为window对象设置了别名),但它确实是一个特殊的属性。 However, if you make the declaration like: 但是,如果您声明如下:

o = {x:1 , y:2 };

then you are setting a property on the global scope (remember, the window object) implicitly. 然后你隐式地在全局范围(请记住, window对象)上设置一个属性。 The two are similar, but different enough. 两者相似,但足够不同。 The delete operator removes an implicit property from an object, but will not delete a variable created on the global object. delete运算符从对象中删除隐式属性,但不会删除在全局对象上创建的变量。

Edit, found a more thorough answer 编辑,找到了更彻底的答案

https://stackoverflow.com/a/4862268/1443478 https://stackoverflow.com/a/4862268/1443478

Since O is already declared and have properties you cannot use delete on the object. 由于O已经声明并且具有属性,因此无法在对象上使用delete。 You can use 您可以使用

var o = {x:1 , y:2 };
delete o.x ; 

and delete properties here is a DEMO for the same. 和删除属性这里是相同的DEMO

first you have to know what is the work of delete operator.let me explain--- 首先你必须知道删除operator.let的工作是什么,我解释一下---

"The delete operator removes a property from an object".here i say it removes an object property not a variable.

in your code you declare a variable.not an object so delete does not work.i think you understand.

o = {x:1 , y:2 }; delete o ;

but the code above is right i think. 但我认为上面的代码是正确的。 why? 为什么? because here o is a property of the global object which is also an object so it work properly.the link which can help you is delete operator 因为这里o是全局对象的属性,它也是一个对象所以它正常工作。可以帮助你的链接是删除操作符

it is my first answer.be happy with coding. 这是我的第一个答案。对编码很满意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM