delete关键字在全局变量上的不同行为 [英] Different behaviour of delete keyword on global variables
本文介绍了delete关键字在全局变量上的不同行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
请考虑以下代码段(小提琴此处):
Please consider the following snippet (fiddle here):
var a;
a = 1;
console.log(delete a); // prints 'false'
b = 1;
console.log(delete b); // prints 'true'
为什么 delete
关键字对全局变量的行为不同 a
和 b
?
Why does the delete
keywords behave differently on the global variables a
and b
?
推荐答案
删除运算符从对象中删除属性。
The delete operator removes a property from an object.
全局变量(不含 var
)是全局对象的属性(通常是窗口
),因此可以删除。
A global variable (without var
) is a property on the global object (typically window
), so can be deleted.
A var
不是全局变量,而是外部作用域中的局部变量 - 不是全局对象的属性 - 所以 delete
不会删除它。来自这些文档:
A var
is not a global variable, but a local variable in the outer scope - not a property of the global object - so delete
does not delete it. From those docs:
x = 42; // creates the property x on the global object
var y = 43; // declares a new variable, y
delete x; // returns true (x is a property of the global object and can be deleted)
delete y; // returns false (delete doesn't affect variable names)
这篇关于delete关键字在全局变量上的不同行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文