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

3
  • 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. Commented Feb 21, 2012 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). Commented Feb 21, 2012 at 10:30
  • possible duplicate of Hash/associative array using several objects as key Commented Feb 21, 2012 at 10:33

1 Answer 1

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;
}();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.