Deleting a window property in IE

后端 未结 4 1538
孤独总比滥情好
孤独总比滥情好 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:50

    I implemented this solution when dealing with caching my own data - the data wasn't much the the frequency of the cache was such that the memory leak might have become an issue. It's costly, but periodically remapping the object was the easiest way for me to be sure it wasn't getting out of hand.

    obj = {a: 1, b: 2, c: 3};
    var max;
    
    function unset(obj, key) {
        try {
            delete obj[key];
        } catch (e) {
            obj[key] = undefined;
        }
    
        max++;
    
        if(max > 200) {
            var keys = Object.keys(obj);
            var len = keys.length;
            var n_obj = {};
            for(var i = 0; i < len; i++) {
                if(obj.hasOwnProperty(keys[i]) && obj[keys[i]] !== undefined) {
                    n_obj[keys[i]] = obj[keys[i]];
                }
            }
            return n_obj;
        }
        return obj;
    }
    
    obj; //{a: 1, b: 2, c: 3}
    obj = unset(obj, "b"); //{a: 1, b: undefined, c: 3} OR {a: 1, c: 3}
    //and then eventually we'll garbage collect and...
    obj = unset(obj, "b"); //{a: 1, c: 3}   
    

    Hopefully, that's useful to some!

提交回复
热议问题