Push onto array with loop in Typescript -


i have following code, answer earlier question: looping through 2d typescript array , making new array value @ index if worked. thought repost because otherwise orig. post complicated.

i don't understand why can't seem push array, or access array outside loop?

  this.days_in_month = [     [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31],    ];    this.month_weekdays = [];   this.days_in_month.foreach(function each(item) {       // console.log(item);       item.foreach(function each(value){         // console.log(value);          let thing: number = value;           for(var = 0; < thing; i++) {             let weekdays: string[] = [ 'm','t','w','t','f','s','s' ];             let wkday: string = (weekdays[(i%7)]);             this.month_weekdays.push(wkday);           };       });   }); 

i think "this.month_weekdays.push(wkday);" should push string wkday array month_weekdays, every value in array days_in_month should loop through weekdays , assign string @ index i%7 index of month_weekdays

so first value in days_in_month month_weekdays should like:

mtwtfssmtwtfssmtwtfssmtwtfssmtw

(and because december has 31 days should final value of month_weekdays)

i think problem occurs because use function() {} syntax without binding this. therefore this.month_weekdays doesn't got correct month_weekdays. there 2 options:

  1. changing function arrow syntax, or
  2. bind this in function() {}

for option number one, code this:

this.days_in_month.foreach((item) => {   // console.log(item);   item.foreach((value) => {     // console.log(value);      let thing: number = value;       for(var = 0; < thing; i++) {         let weekdays: string[] = [ 'm','t','w','t','f','s','s' ];         let wkday: string = (weekdays[(i%7)]);         this.month_weekdays.push(wkday);       };   }); 

});

you should able access month_weekdays outside loop. happen function() {} syntax have own this, therefore have bind this outer scope function(){} refers correct this. on other hand, arrow syntax shorter syntax function(){} , not bind own this, arguments, super, or new.target; no binding of this required.

for option number two, code this:

this.days_in_month.foreach(function(item) {   // console.log(item);   item.foreach(function(value) {     // console.log(value);      let thing: number = value;       for(var = 0; < thing; i++) {         let weekdays: string[] = [ 'm','t','w','t','f','s','s' ];         let wkday: string = (weekdays[(i%7)]);         this.month_weekdays.push(wkday);       };   }.bind(this)); }.bind(this)); 

Comments