Thursday 5 May 2011

Unset function in Javascript

Here's my version of an occasionally required function, Unset(). I wrote this before I found the version on phpjs.org so I thought I might as well publish it online because it's easier to make sense of than the one they wrote.

To briefly explain how it works:

There are three different things that you might want to "unset" in javascript - 1. Individual array elements, 2. a property of an object (which could be a variable, function or an object) and 3. a normal variable, which actually may hold a simple value like 1 or more complex items like an array or an object reference/definition. Each one of these different types of variable are unset in a different way:

1. myarray.splice(index,1);
myarray is the name of an array. index is the index number of the item in the array starting from 0. And the second argument (1), is the number of items to splice/cut out of the array.

2. delete myclass.myproperty;
This simply deletes the variable myproperty from the object myclass. Of course, in javascript, myproperty could contain a simple value, a method or an object.

3. myvar = undefined;
If I've previously defined a variable like so: var myvar = "hello"; then I can undefine it by setting it to the javascript equivalent of null which is "undefined". You can also unset a whole array/object using the same command.

Anyway, here's my general purpose javascript unset() function:

/**
* Unset variables, objects, array elements and object 
* properties in Javascript much like you can in PHP
* @author Ahmad Retha
* @license Public Domain
*/
function unset()
{
    for(var _i = 0; _i < unset.arguments.length; _i++){
        //where item to unset is an array element (var[index])
        if(_m = unset.arguments[_i].match(/(\w+)\[(\d+)\]/)){
            eval(_m[1] + ".splice(" + _m[2] + ", 1);");
        //where item to unset is an object item
        }else if(unset.arguments[_i].match('.')){
            eval("delete " + unset.arguments[_i] + ";");
        //where item to unset is a normal variable
        }else{
            eval(unset.arguments[_i] + " = undefined;");
        }
    }
}

You pass the names of the variables, classes, elements of arrays and object properties as strings and it removes them. You can pass as many arguments to the unset() function as you like. Usage example:

var x = 1;
var y = ['a','b','c'];
var z = {'one':1, 'two':2, 'three':3};

unset("x", "y[1]", "z.three");

Variable x is now undefined. Array y now holds two elements, a and c. Class z is now an object with two properties.