Javascript'delete'在迭代循环中不起作用 [英] Javascript 'delete' doesn't work inside iteration loop

查看:80
本文介绍了Javascript'delete'在迭代循环中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一名使用JavaScript的C / C ++ / Java程序员。

I'm a C/C++/Java programmer working with JavaScript.

我正在尝试编写一个删除对象'obj的所有属性的函数。我已阅读如何快速清除Javascript对象?并且看到有两个答案:(1)创建一个新的'obj'(我不想做,因为我的代码是在移动浏览器中运行的高性能程序,我想最小化垃圾采集); (2)迭代循环中对象的属性并删除属性。后一种方法在Chrome 12中不起作用。

I'm trying to write a function that will delete all properties of an object 'obj'. I've read the posting on "How to quickly clear a Javascript Object?" and saw that there are two answers: (1) creating a new 'obj' (which I don't want to do because my code is a high-performance program running in a mobile browser, and I want to minimize garbage collection); and (2) iterating over the properties of an object in a loop and deleting the properties. This latter approach doesn't work in Chrome 12.

请考虑以下代码:

var foo = {};
foo['baz'] = 'bar';
console.log("1. foo.baz = " + foo.baz);

delete foo.baz;
console.log("2. foo.baz = " + foo.baz);

foo['baz'] = 'bar';
console.log("3. foo.baz = " + foo.baz);

for (prop in foo)
{
    if (foo.hasOwnProperty(prop))
    {
        console.log("deleting property " + prop);
        delete foo.prop;
    }
}
console.log("4. foo.baz = " + foo.baz);

这会在Chrome 12的我的控制台中产生以下结果:

This produces the following result in my console on Chrome 12:

1. foo.baz = bar
2. foo.baz = undefined
3. foo.baz = bar
deleting property baz
4. foo.baz = bar

为什么不在循环中删除foo.baz?

Why doesn't foo.baz get deleted inside the loop?

推荐答案

您以错误的方式查找。您需要使用括号表示法

You lookup the key in the wrong way. You need to use the bracket notation:

delete foo[ prop ];

但是,您不需要遍历对象中的每个属性。 null 对象引用本身就好了。垃圾收集器会照顾你。

However, you don't need to loop over every property within an object. It's just fine to null the object reference itself. The garbage collector will take care of you.

foo = null; // done

谈论高性能,这就是你想要的方式。

Talking of high performance, that is the way you want to do.

这篇关于Javascript'delete'在迭代循环中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆