Answers
Dec 28, 2006 - 06:37 AM
I haven't found a way to declaratively remove a variable as you're describing. When it comes to javascript, I try to stick with local variables so I don't get "unexpected" results if I want to use the same variable name in a different scope.
It may just require you to change the scope of the variables to prevent the problems you're having.
Ric
Dec 28, 2006 - 06:55 AM
For instance, I am looping through an array with named elements (properties...?) and doing something to each of them.
I want to remove some elements from it before doing that.
But luckily I found the answer myself:
delete
You can:
delete x // Removes the variable x
delete x[i] // Removes the element with index i from array x
delete x.p // Removes the property p from object / array x
Quite simple - and works in IE and FF - but so strange that so relatively few seems to know of this.
Jan 04, 2007 - 11:25 AM
I'm glad you found a workable answer!
Ric
Jan 09, 2007 - 10:49 AM
I have to correct my previous answer though, as the transition from theory to praxis once again proved quirky.
I tried to remove a variable or object with the 'delete x' statement, but nothing happened. I didn't get a warning nor error message and the variable continued to exist with the same value!
It seems to work with properties and array elements though. The deleted property / element will have the value 'null' and 'undefined' if tested afterwards. (Meaning that both 'x.y == null' and 'x.y === undefined' evaluates to true after 'delete x.y')
Jakob
Nov 19, 2007 - 11:01 PM
var x=1; delete x; //false
y=2; delete y; // true
see http://developer.mozilla.org/en/docs/...
however, length property of array is not affected, i.e:
color= new Array("red","green","blue");
delete color[2]; //"green" is deleted and no longer exists in color
alert(color.length); // !! 3 !!
Nov 20, 2007 - 01:41 AM
Dec 11, 2008 - 12:02 PM
color.splice(1, 2); // deletes 2 elements from index 1 (leaving "red" in the array)
Jan 14, 2009 - 04:28 AM
delete x[i] // Removes the element with index i from array x
delete x.p // Removes the property p from object / array x
var x=1; delete x; // Doesn't work
y=2; delete y; // Works
However, be careful when testing the lenght property of an array after deleting an element this way; i.e:
color = new Array("red","green","blue");
delete color[2]; // "green" is deleted and no longer exists in color
alert(color.length); // Still reports 3!!
Thanks,
Jakob
May 22, 2009 - 01:16 AM
var x = new Array();
....
x.splice(....
Regards,
Alex
By
i need it to
Add New Comment