Deleting a window property in IE
我找不到关于这个问题的任何信息;为什么下面的代码在IE中不起作用?
1 2 3 | window.x = 45; delete window.x; // or delete window['x']; |
IE报告"对象不支持此操作"错误。它与在IE问题中对窗口属性进行迭代有什么关系吗?
加斯伯对他完成的解决方案发表了评论,但我认为作为一个实际的答案,它值得一呼:
1 2 3 4 5 6 7 8 | try { delete window.x; } catch(e) { window["x"] = undefined; } |
有意思的是,我今晚只是撞到它。在IE上引发了异常,而不是在Firefox上。我怀疑这个解决方法会泄露内存,所以要谨慎使用。
有人问,为什么不分配未定义的?如果您想稍后枚举键,这很重要(尽管如果您依赖于解决方案,则键枚举仍然不会执行您想要的操作…)。但无论如何,要强调删除和简单地分配未定义之间的区别(http://jsfiddle.net/fschwiet/t4akl/):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | 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')); |
产生输出:
1 2 3 | cleared has key a deleted has a? false cleared has a? true |
我会这样做:
1 2 3 4 | window[x] = undefined; try{ delete window[x]; }catch(e){} |
这有帮助吗?
1 2 3 | window.x = 45; alert(window.x); window.x = null; |
我在ie和window.x中尝试过,它确实有一个值,这证明它是可以设置的。将该值设置为空是清除该值的最佳选择。
我在处理缓存自己的数据时实现了这个解决方案——数据并不多,缓存的频率可能会导致内存泄漏。这是昂贵的,但定期重新映射对象是最简单的方法,以确保它不会失控。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 | 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} |
希望这对一些人有用!