Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript 'delete' doesn't work inside iteration loop

Tags:

javascript

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

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.

Consider the following code:

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);

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

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

like image 880
stackoverflowuser2010 Avatar asked Jul 21 '11 17:07

stackoverflowuser2010


People also ask

Why you shouldn't use delete JavaScript?

it's only effective on an object's properties, it has no effect on variable or function names. The delete operator shouldn't be used on predefined JavaScript object properties like window , Math , and Date objects. It can crash your application.

How do you delete an element from an array loop?

Use unset() function to remove array elements in a foreach loop. The unset() function is an inbuilt function in PHP which is used to unset a specified variable.

Does delete return value?

The delete operator has void return type does not return a value.

How does delete work in JavaScript?

The delete operator removes a property from an object. If the property's value is an object and there are no more references to the object, the object held by that property is eventually released automatically.


2 Answers

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

delete foo[ prop ];

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.

like image 93
jAndy Avatar answered Oct 12 '22 23:10

jAndy


This line delete foo.prop is incorrect. foo has no property named prop in this case. Using brackets delete foo[prop].

like image 41
Joe Avatar answered Oct 12 '22 23:10

Joe