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

后端 未结 10 1392
死守一世寂寞
死守一世寂寞 2020-12-13 06:02

JSLint is not passing this as a valid code:

/* global someVar: false */
if (typeof someVar === \"undefined\") {
    var someVar = \"hi!\";
}
<
10条回答
  •  攒了一身酷
    2020-12-13 06:07

    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';
    

提交回复
热议问题