Javascript 检查全局变量是否存在的正确方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11596315/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 06:28:08  来源:igfitidea点击:

What is the correct way to check if a global variable exists?

javascriptglobal-variablesjslint

提问by Ebrahim Byagowi

JSLint is not passing this as a valid code:

JSLint 没有将此作为有效代码传递:

/* global someVar: false */
if (typeof someVar === "undefined") {
    var someVar = "hi!";
}

What is the correct way?

什么是正确的方法?

回答by bigoldbrute

/*global window */

if (window.someVar === undefined) {
    window.someVar = 123456;
}

if (!window.hasOwnProperty('someVar')) {
    window.someVar = 123456;
}

回答by gvlasov

/**
 * @param {string} nameOfVariable
 */
function globalExists(nameOfVariable) {
    return nameOfVariable in window
}

It doesn't matter whether you created a global variable with var foo or window.foo — variables created with var in global context are written into window.

无论你是用 var foo 还是 window.foo 创建了一个全局变量都没有关系——在全局上下文中用 var 创建的变量被写入到 window 中。

回答by mrak

If you are wanting to assign a global variable only if it doesn't already exist, try:

如果您只想分配一个不存在的全局变量,请尝试:

window.someVar = window.someVar || 'hi';

or

或者

window['someVar'] = window['someVar'] || 'hi';

回答by gion_13

try

尝试

variableName in window

or

或者

typeof window[variableName] != 'undefined'

or

或者

window[variableName] !== undefined

or

或者

window.hasOwnProperty(variableName)

回答by bfavaretto

I think this is actually a problem with JSLint. It will issue the following error:

我认为这实际上是 JSLint 的一个问题。它将发出以下错误:

Unexpected 'typeof'. Compare directly with 'undefined'.

意外的“typeof”。直接与“未定义”进行比较。

I believe this is bad advice. In JavaScript, undefinedis a global variable that is, usually, undefined. But some browsers allow scripts to modify it, like this: window.undefined = 'defined'. If this is the case, comparing directly with undefinedcan lead to unexpected results. Fortunately, current ECMA 5 compliant browsers do not allow assignments to undefined(and will throw an exception in strict mode).

我相信这是一个糟糕的建议。在 JavaScript 中,undefined是一个全局变量,通常是未定义的。但是,一些浏览器允许脚本来修改它,就像这样:window.undefined = 'defined'。如果是这种情况,直接比较undefined可能会导致意想不到的结果。幸运的是,当前的 ECMA 5 兼容浏览器不允许赋值undefined(并且会在严格模式下抛出异常)。

I prefer typeof someVar === "undefined", as you posted, or someVar in windowas Susei suggested.

我更喜欢typeof someVar === "undefined",正如您发布的那样,或者someVar in window像 Susei 建议的那样。

回答by Vatev

if (typeof someVar === "undefined") {
    var someVar = "hi!";
}
if (typeof someVar === "undefined") {
    var someVar = "hi!";
}

will check if someVar(local or global) is undefined.

将检查someVar(本地或全局)是否未定义。

If you want to check for a global variable you can use

如果要检查全局变量,可以使用

if(window['someVar'] === undefined) {
    ...
}

assuming this is in a browser :)

假设这是在浏览器中:)

回答by Michael

bfavaretto is incorrect.

bfavaretto 是不正确的。

Setting the global undefined to a value will not alter tests of objects against undefined. Try this in your favorite browsers JavaScript console:

将全局 undefined 设置为一个值不会改变对象对 undefined 的测试。在您最喜欢的浏览器 JavaScript 控制台中试试这个:

var udef; var idef = 42;
alert(udef === undefined); // Alerts "true".
alert(idef === undefined); // Alerts "false".
window.undefined = 'defined';
alert(udef === undefined); // Alerts "true".
alert(idef === undefined); // Alerts "false".

This is simply due to JavaScript ignoring all and any values attempted to be set on the undefined variable.

这仅仅是因为 JavaScript 忽略了所有试图在未定义变量上设置的值。

window.undefined = 'defined';
alert(window.undefined); // Alerts "undefined".

回答by Prem Anand

This would be a simple way to perform the check .

这将是执行检查的简单方法。

But this check would fail if variableNameis declared and is assigned with the boolean value: false

但是如果variableName声明并分配了boolean value: false

if(window.variableName){

}