0

I'm having an issue with my code. Been trying for some time to get a value from an object or arrays. I'm using a loop to get through each value in the array from the object. I get the value when I hard code the position on the value but undefined when I use the value 'num' from the loop?

for(var num = 0; num <= 6; num++){
  // sets the date from the start of the week.
  newDate = moment().startOf('week').weekday(num).toDate();

  if(timesheet.timesheet.start[num] === ''){
    ....
  } else { 
    Times.create(timesheet, function(err, newTimes) {
      if(err){
        console.log(err); 
      } else {
        newTimes.timesheet.id = newTimesheet.id;
        // Prints the value fine
        console.log(timesheet.timesheet.start[0]);
        // Gives me undefined?
        newTimes.start = timesheet.timesheet.start[num];
        newTimes.end = "On";
        newTimes.save();
        newTimesheet.times.push(newTimes);
        newTimesheet.save();
      }

    }); 
  }
}
Adam Konieska
  • 2,805
  • 3
  • 14
  • 27
SmiffyKmc
  • 801
  • 1
  • 16
  • 34
  • 1
    see: http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – Hacketo Mar 31 '16 at 13:53
  • @Hacketo thanks for showing me the link. Been trying to read up about bind() but can't really get the idea of it. Been trying to teach myself javascript. Would I be right in saying that where I have the 'newTimes.start = timesheet.timesheet.start[num];' I should have it using 'bind(num)'? Thank you for helping. – SmiffyKmc Mar 31 '16 at 14:27
  • 1
    You don't need `bind`, `bind` is used when you need to save the `this` context, what you can use is the first answer of the post, it's about moving your code inside a function and then call that function inside the loop. – Hacketo Mar 31 '16 at 14:32
  • Thanks @Hacketo. I'll give that a shot! – SmiffyKmc Mar 31 '16 at 14:35

0 Answers0