Search code examples
javascriptgoogle-apps-scriptiife

trying to implement an array within an array of of objects


In Google Apps JS. I would like to implement an array of objects, each with properties and methods. One of the properties needs to be an array of objects and I would like to be able to access this array by using methods in the parent array.

So far my best efforts is:

function myFunction () {
  var teamNo = 3;
  var allNames =["n1","n2","n3","n4"] ;
  var createnames = function () {
    var names = [];            
    for ( var j = 0; j <=3 ; j ++) {      
      (function (j) {
        var localNames = ["local1-names"+j,"local2-names"+j];
        names[j] = (function (player){
          return {
            namArr: localNames,
            name:   allNames[j],         
            addName: (function (player){
              localNames.push(player);
            }) (player),
             team:   teamNo            
          };         
        });
      }) (j);
    }
    return names;
  }
  var myname = createnames();
  var foo = myname[0]().namArr;
  var foo1 = myname[1]().namArr;
  myname[1]().addName("added");
  var foo2 = myname[1]().namArr;
  var foo3 = myname[2]().namArr;
  var debug = true;
}

As soo as I add the code to implement the sub array I get a runtime error saying that addName does not exist.


Solution

  • You're invoking this immediately:

    addName: (function (player) {
        localNames.push(player);
    })(player)
    

    instead of assigning it:

    addName: function (player) {
        localNames.push(player);
    }
    

    Also, each names[] function takes a player, and so does the addPlayer() function, making the names[] parameter unreachable. If you're not going to pass anything to the names[] functions, then remove the parameter.

    And I'd suggest using named functions instead of inlined IIFEs.