HOWTO: Convert between JScript Array and VB Safe Array

I recently got a question about how to manipulate the LIST data type within JScript since my sample code only illustrated VBScript.

Well... one reason why that example is in VBScript is because LIST manipulation (a VB SafeArray) is more straight forward and requires much less code in VBScript.

Then, there is Microsoft documentation which says the following time and again (and echo'd in lots of other places):

There is currently no way to convert a JavaScript array into a VBArray

Really? I could not believe it. A quick search of the Internet turned up no results of how to do this, either... so it sounds like a good challenge to me. :-)

I racked my brain a little, and I came up with the following built-in solution to the problem of converting a JScript array into a VB SafeArray. Yes, I know it is not efficient, but for casual conversion for the purposes of IIS configuration, it definitely suffices. And it works on Windows 2000 on up with no additional requirements, a definite bonus from a dependency/ubiquity point-of-view.

See the following JScript code which manipulates the IIS ScriptMaps property (a VB SafeArray) by first converting the SafeArray into JScript array, then manipulating it in JScript, and finally converting it back to a VB SafeArray for use by the Scriptmaps LIST property.

Enjoy!

//David

 var objRoot = GetObject( "IIS://localhost/w3svc/1/root" );
var arrVB = objRoot.Get( "ScriptMaps" );

//
// Convert from VB Array for manipulation in JScript
//
var arrJS = VB2JSArray( arrVB );
//
// Insert a test Value at end of ScriptMaps
//
arrJS[ arrJS.length ] = ".test,value,0";
//
// Convert back to VB Array to save by IIS
//
objRoot.ScriptMaps = JS2VBArray( arrJS );
objRoot.SetInfo();

function VB2JSArray( objVBArray )
{
    return new VBArray( objVBArray ).toArray();
}

function JS2VBArray( objJSArray )
{
    var dictionary = new ActiveXObject( "Scripting.Dictionary" );
    for ( var i = 0; i < objJSArray.length; i++ )
    {
        dictionary.add( i, objJSArray[ i ] );
    }

    return dictionary.Items();
}