skip to Main Content

I am trying to figure out a way to assign tile values to my tictactoe cell variables equivalent to the variable characters themselves in a more concise manner. Each variable should be equivalent to get.elementById("variable name here. i.e. a2").value; I feel there is a better way than to write a verbose code block assigning the values individually and would like to understand this better conceptually if it is even possible.

Note I would like to run these through a loops to assign each variable its own independent value according to the element ID. So tiles.a1 = get.elementById("a1").value;

Here is the small snippet of source code that im building:

var tiles = new Object(); tiles.assignTile = new function() { tiles.a1, a2, a3, b1, b2, b3, c1, c2, c3 = ''; }

I am currently at the learning stage of basic programming concepts so please elaborate on your response to help me understand better. In the meantime I will scavenge google 🙂

Hope to hear some bright ideas!

Thanks!

2

Answers


  1. You can create a constructor function to initialize your object. Note that obj.prop and obj[prop] are equivalent. Look at the example.

    function myTitles() { //constructor function
      for (var i = 0, arg; arg = arguments[i]; ++i) { //arguments is automatic variable 
        //'this' is an alias of the newly created object 
        this[arg] = arg; //or whatever which depends on the arg
      }
    }
    
    var titles = new myTitles('a1', 'a2', 'b1', 'b2');//create a new object with properties. 'new' is required.
    console.log(titles);
    console.log(titles.a1);
    Login or Signup to reply.
  2. You can create a constructor function to initialize your object. Note that obj.prop and obj[prop] are equivalent. Look at the example.

    function myTitles() { //constructor function
      for (var i = 0, arg; arg = arguments[i]; ++i) { //arguments is automatic variable 
        //'this' is an alias of the newly created object 
        this[arg] = arg; //or whatever which depends on the arg
      }
    }
    
    var titles = new myTitles('a1', 'a2', 'b1', 'b2');//create a new object with properties. 'new' is required.
    console.log(titles);
    console.log(titles.a1);

    example of the above code is given

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search