0

I have an array of 'users' that gets data added/deleted to it. I also have an object 'temp' that will generate a methods based on how many indexes are in the array.

Here's the code I have so far:

var users = [1, 2];
var index = users.length;

var temp = {};

function newTemp(object){
 var index = users[object]; //assigns an index #
 if(index === undefined){
  index = users.length;
  users[object] = index;
 }
 users[index] = object;
 for (var i = 0; i < users.length - 1; i++){
   temp.['check' + i] = function(){console.log('checking ' + i);}
  }
}

newTemp(index);

Ideally, based on how much data is in 'users' I would like 'temp' to contain something like this:

var temp = {
    check0 : function(){
        console.log('checking ' + 0);
    },
    check1 : function(){
        console.log('checking ' + 1);
    }
}
Robbie Fikes
  • 409
  • 4
  • 15
  • 1
    Do you know how to use a console? The error message in the console is `js:26 Uncaught SyntaxError: Unexpected token [` There is no dot in bracket notation. And when you remove that all the console.log lines will log the same exact number. `temp.['check' + i]` should be `temp['check' + i]` – epascarello Oct 11 '16 at 03:23
  • And why your loop will console.log the same thing: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Oct 11 '16 at 03:25
  • In the for-loop I want to generate the name 'check0, check1, etc....' so that it creates 'temp.check0 = ..., etc...' – Robbie Fikes Oct 11 '16 at 03:27
  • So did you remove the dot to get rid of the error?? You also are using length which is greater than the number of users you have.... Remember that arrays start at index zero, not one – epascarello Oct 11 '16 at 03:30
  • Your right! Thanks you! I'll add -1 for the length as well – Robbie Fikes Oct 11 '16 at 03:37

0 Answers0