Deleting a window property in IE

后端 未结 4 1537
孤独总比滥情好
孤独总比滥情好 2021-01-30 08:25

I can\'t find any information on this issue; why doesn\'t the following code work in IE?

window.x = 45;
delete window.x;
// or delete window[\'x\'];
4条回答
  •  别那么骄傲
    2021-01-30 08:59

    Gasper made a comment with the solution he finished on, but I think its worth calling out as an actual answer:

    try 
    { 
        delete window.x; 
    } 
    catch(e) 
    { 
        window["x"] = undefined; 
    }
    

    Interesting issue, I was just banging my head against it tonight. The exception is thrown on IE but not Firefox. I would suspect this workaround leaks memory, so use sparingly.

    It was asked, why not just assign undefined? It matters if you want to enumerate the keys later (though if you're relying on the workaround, the key enumeration still won't do what you want...). But anyhow, to highlight the difference between delete and simply assigning undefined (http://jsfiddle.net/fschwiet/T4akL/):

    var deleted = {
        a: 1
    };
    
    var cleared = {
        a: 1
    };
    
    delete deleted["a"];
    cleared["a"] = undefined;
    
    for(var key in deleted) {
        console.log("deleted has key", key);
    }
    
    for(var key in cleared) {
        console.log("cleared has key", key);
    }
    
    console.log("deleted has a?", deleted.hasOwnProperty('a'));
    console.log("cleared has a?", cleared.hasOwnProperty('a'));
    

    produces output:

    cleared has key a
    deleted has a? false
    cleared has a? true 
    

提交回复
热议问题