在Typescript中使用循环推送到数组

时间:2017-08-18 17:01:09

标签: arrays typescript

我有以下代码,这是我之前的问题的答案:Looping through 2d Typescript array and making new array from value at index只要它有效。我以为我会重新发布,因为否则原来。帖子会变得太复杂。

我不明白为什么我似乎无法推送到数组,或者在循环外访问数组?

-- imports ...

routes :: ScottyM ()
routes = do 
    post "data/:id" $ do
        id <- param "id"
        -- HERE IS WHERE I GET CONFUSED
        -- This is what I want to do
        db <- open "store.db"
        exec db "INSERT INTO Store (id, value) VALUES (" <> id <> ", 'Test Value');" -- I know there is SQL Injection here I will learn about parameterized queries in haskell next
        close db
        -- END THE PART I AM CONFUSED BY
        text $ "created a record with " <> id <> " id."

main :: IO()
    scotty 3000 routes

我认为&#34; this.month_weekdays.push(wkday);&#34;应该将字符串wkday推送到数组month_weekdays,以便对于数组中的每个值days_in_month它应循环工作日并将索引i%7处的字符串分配给month_weekdays的索引i

因此,对于days_in_month month_weekdays中的第一个值,应该如下所示:

MTWTFSSMTWTFSSMTWTFSSMTWTFSSMTW

(因为12月有31天,这也应该是month_weekdays的最终值)

2 个答案:

答案 0 :(得分:1)

我认为问题出现是因为您使用function() {}语法而不绑定this。因此,this.month_weekdays并未完全正确month_weekdays。有两种选择:

  1. 将您的功能更改为箭头语法或
  2. this
  3. 中绑定function() {}

    对于第一个选项,您的代码将如下所示:

    this.days_in_month.forEach((item) => {
      // console.log(item);
      item.forEach((value) => {
        // console.log(value);
    
        let thing: number = value;
          for(var i = 0; i < thing; i++) {
            let weekdays: string[] = [ 'M','T','W','T','F','S','S' ];
            let wkday: string = (weekdays[(i%7)]);
            this.month_weekdays.push(wkday);
          };
      });
    

    });

    您应该能够在循环外访问month_weekdays。会发生什么function() {}语法有自己的this,因此您必须绑定外部作用域中的this,以便function(){}引用正确的this 。另一方面,箭头语法的语法比function(){}短,并且不绑定自己的thisargumentssupernew.target;因此,不需要this的绑定。

    对于第二个选项,您的代码将如下所示:

    this.days_in_month.forEach(function(item) {
      // console.log(item);
      item.forEach(function(value) {
        // console.log(value);
    
        let thing: number = value;
          for(var i = 0; i < 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));
    

答案 1 :(得分:1)

在没有this的情况下工作:

const WEEK_DAYS: string[] = ['M', 'T', 'W', 'T', 'F', 'S', 'S'];
var 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]
];

let month_weekdays = [];
days_in_month.forEach(item => {
  item.forEach(value => {
    for (var i = 0; i < value; i++) {
      let wkday: string = WEEK_DAYS[(i % 7)];
      month_weekdays.push(wkday);
    };
  });
});