How to unset a JavaScript variable?

后端 未结 11 2023
执笔经年
执笔经年 2020-11-22 04:16

I have a global variable in JavaScript (actually a window property, but I don\'t think it matters) which was already populated by a previous script but I don\'t

11条回答
  •  清酒与你
    2020-11-22 04:54

    TLDR: simple defined variables (without var, let, const) could be deleted with delete. If you use var, let, const - they could not be deleted neither with delete nor with Reflect.deleteProperty.

    Chrome 55:

    simpleVar = "1";
    "1"
    delete simpleVar;
    true
    simpleVar;
    VM439:1 Uncaught ReferenceError: simpleVar is not defined
        at :1:1
    (anonymous) @ VM439:1
    var varVar = "1";
    undefined
    delete varVar;
    false
    varVar;
    "1"
    let letVar = "1";
    undefined
    delete letVar;
    true
    letVar;
    "1"
    const constVar="1";
    undefined
    delete constVar;
    true
    constVar;
    "1"
    Reflect.deleteProperty (window, "constVar");
    true
    constVar;
    "1"
    Reflect.deleteProperty (window, "varVar");
    false
    varVar;
    "1"
    Reflect.deleteProperty (window, "letVar");
    true
    letVar;
    "1"
    

    FF Nightly 53.0a1 shows same behaviour.

提交回复
热议问题