views:

270

answers:

4

I've declared Javascript arrays in such a way that I could then access them by a key, but it was a long time ago, and I've forgotten how I did it.

Basically, I have two fields I want to store, a unique key, and its value. I know there is a way to do it.. something like:

var jsArray = new {key: 'test test', value: 'value value'},
              new {key: 'test 2', value: 'value 2'};

and accessed like:

value = jsArray[key]

Can someone remind me?

+6  A: 

You can do it in different ways:

var a = {'a':0, 'b':1, 'c':2};

var b = new Array();
b['a'] = 0;
b['b'] = 1;
b['c'] = 2;

var c = new Object();
c.a = 0;
c.b = 1;
c.c = 2;
CMS
It's worth noting that a['b'] and a.b are identical, in fact a[0] is the same as a.0 it's only the JS grammar that prevents you from doing that :D
olliej
Yes, internally are accessed the same way, it's your choice witch flavor use :D
CMS
+1  A: 
var myFancyDictionary = {
  key: 'value',
  anotherKey: 'anotherValue',
  youGet: 'the idea'
}
aaaidan
+2  A: 

If you are already using Prototype, try using its Hash. If using jQuery, try using Map.

tvanfosson
A: 

Here is a JavaScript class that provides a simple dictionary.

if( typeof( rp ) == "undefined" ) rp = {};

rp.clientState = new function()
{
    this.items = new Object();
    this.length = 0;

    this.set = function( key, value )
    {
        if ( ! this.keyExists( key ) )
        {
            this.length++;
        }
        this.items[ key ] = value;    
    }

    this.get = function( key )
    {
        if ( this.keyExists( key ) )
        {
            return this.items[ key ];
        } 
    }

    this.keyExists = function( key )
    {
        return typeof( this.items[ key ] ) != "undefined"; 
    }

    this.remove = function( key )
    {
        if ( this.keyExists( key ) )
        {
            delete this.items[ key ];
            this.length--;   
            return true;
        }
        return false;
    }

    this.removeAll = function()
    {
        this.items = null;
        this.items = new Object();
        this.length = 0;
    }
}

Example use:

// Add a value pair.
rp.clientState.set( key, value );

// Fetch a value.
var x = rp.clientState.Get( key );

// Check to see if a key exists.
if ( rp.clientState.keyExists( key ) 
{
    // Do something.
}

// Remove a key.
rp.clientState.remove( key );

// Remove all keys.
rp.clientState.removeAll();
rp
This seems a little heavy-handed. Any particular reason you need those functions to do all those things?
aaaidan
aaaidan--what would you leave out?
rp