Search code examples
javascriptarraysarray-push

push values into an array dynamically with javascript


I'm have trouble finding a way to push values into an array dynamically. I have given the following situation:

var get_anchors= new Array('pitzel','mitzel','sizzle') 

current_anchor= pics[key].anchor; //has the value 'sizzle'

get_anchors[current_anchor].push(new Array('sizzle2','sizzle3'))

Javascript fails and says get_anchors[current_anchor] is undefined

How can I make get_anchors[current_anchor] work. Or is there a different way to get this done?

The desired result should look like 'pitzel','mitzel','sizzle'['sizzle2','sizzle3]


Solution

  • Based on your comment it looks like you want a hash map instead of an array. You can use an object for this:

    var anchors = {
        'pitzel': [],
        'mitzel': [],
        'sizzle': []
    };
    

    Then you can do:

    anchors[current_anchor].push('sizzle2', 'sizzle3');
    

    or assuming that anchors does not have a property with the value of current_anchor, simply assign a new array:

    anchors[current_anchor] = ['fooX', 'fooY'];
    

    Of course you can populate the object dynamically as well. Have a look at Working with Objects for more information.