1

How to use the functionality of dictionary in JavaScript?

Look at this question the specified way is working, but I am setting the function instance as a key like this:

Scale = function ()
{
    this.Collections = {};
    this.IndexTracker = {};
    this.UpdateIndex = function ()
    {
        var index = 0;
        for ( var i = 0; i < this.Collections.length; i++ )
        {
            this.SetIndex( this.Collections[i], index++ );
        }
    }
    this.SetIndex = function ( obj, value )
    {
        this.IndexTracker[obj] = value;
    }
    this.GetIndex = function ( obj, value )
    {
        return this.IndexTracker[obj];
    }
}

this.Collections will hold the some function instance.

The problem here is the function instance is overwritten by the next function instance in this.Collections. The the length of the Collections always is 1. How to solve this?

enter image description here

Community
  • 1
  • 1
BalaKrishnan웃
  • 4,337
  • 7
  • 30
  • 51
  • It might be a scoping issue - use the `var` keyword so the variables (`this.Collections`,etc) only exist within the scope of the function (object), rather than being saved into the global scope. – Anthony Grist Feb 21 '12 at 10:30
  • 1
    Keys will be treated as strings. If you a different data type as key, it will be converted to a string. The default string representation is `[object Object]` so you have think about something else to use as key (e.g. use your own object serialization). – Felix Kling Feb 21 '12 at 10:30
  • possible duplicate of [Hash/associative array using several objects as key](http://stackoverflow.com/questions/6983436/hash-associative-array-using-several-objects-as-key) – Felix Kling Feb 21 '12 at 10:33

1 Answers1

1

This is an example:

var Scale = function () {
    var _Collections = {},
    _IndexTracker = {},
    ret = function () {
        function UpdateIndex() {
            var index = 0,i,l;
            for (i = 0,l=_Collections.length; i < l; i++) {
                this.SetIndex(_Collections[i], index++);
            }
        }
        function SetIndex(obj, value) {
            _IndexTracker[obj] = value;
        }
        function GetIndex(obj, value) {
            return _IndexTracker[obj];
        }
        return {
            UpdateIndex : UpdateIndex,
            SetIndex : SetIndex,
            GetIndex : GetIndex
        };
    };
    return ret;
}();
vvtommy
  • 46
  • 2