Search code examples
javascriptarraysobjectcopyfill

Creating an array with copy of object (Javascript)


I'm trying to write a "universal" array filler that fills an array with a given object. I simulted a class in javascript and now I want to write a function that fills the array with types of that class

function fillArray(theArrayToFill,amount,theObject) {
for ( var i = 0; i != amount; ++i ) 
    {theArrayToFill.push(theObject);}
}

But fillArray (theArray,3,new Enemy(0,0)); fills the array with a reference to that object "enemy" and that's not what I want, I want an exact copy, but when I mutate object 0, object 2 may not change.

Please Help Thanks


Solution

  • If you are using Underscore, it provides a clone helper function.

    function fillArray(theArrayToFill,amount,theObject) {
    for ( var i = 0; i != amount; ++i ) 
        {theArrayToFill.push(_.clone(theObject));}
    }