如何删除或取消设置 Javascript 变量

How to delete or unset a Javascript variable

我在 Javascript 中有一个全局变量,它已经由之前的函数填充。

我知道我可以给这个变量无意义的值来测试,但我认为还有另一种方法。例如,我放了 some_var = undefined 并且它用于测试 typeof some_var == "undefined"

有没有更专业的方法来解决这个问题?

像这样定义你的变量:

window.some_var = 1;

... 或者像这样:

window["some_var"] = 1;

然后,你可以这样删除它们:

delete some_var;

... 或者像这样:

delete window.some_var;

... 或者像这样:

delete window["some_var"];

注:

如果您这样定义变量,

delete NOT 是否有效:

var some_var = 1;

I have a global variable in Javascript which is already populated by previous function

如果是全局的那么

delete window["variable-name"]; //should do the trick

window.x = 1; //equivalent to var x = 1; if x is global
delete window.x;

如果你只有全局变量的名字那么

window["x"] = 1; //equivalent to var x = 1; if x is global
delete window.x

delete window.some_var; 应该可以解决问题。