如何在Svelte3和Javascript中将复杂的计算数组返回给箭头函数?

时间:2019-05-06 20:34:48

标签: javascript arrays arrow-functions svelte

由于新版本的Svelte v3,我正在尝试将我的v2代码转换为新版本。我已经将计算部分转换为Javascript箭头功能。我想将函数返回的值设置为箭头函数所在的变量。我也尝试这样做:

calendar = () => {...}

,但在这种情况下,浏览器会解释箭头 作为默认方法。

$: calendar => {
  // Function to calculate the calendar which updates every change
  let calendarArr = [];
  const offset = new Date(
    selectedDate.getFullYear(),
    selectedDate.getMonth(),
    1
  ).getDay();
  //number of days in selected month
  const days =
    32 -
    new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 32).getDate();
  //for each potential cell(empty cells + day cells)
  for (let d = 0; d < days + offset; d++) {
    //start new row if 0th, 7th, 14th etc day
    if (d % 7 == 0) calendarArr.push([]);
    //push cell into the row
    calendarArr[Math.trunc(d / 7)].push(
      d - offset < 0
        ? null
        : new Date(
            selectedDate.getFullYear(),
            selectedDate.getMonth(),
            d - offset + 1
          )
    );
  }
  console.log(calendarArr);
  return calendarArr; // -> I want to set this as the calendar value
};

2 个答案:

答案 0 :(得分:1)

反应式语句($:)不必是计算为单个值的表达式。您可以在反应式语句中计算calendarArr,然后将该值分配给组件中的另一个变量。

示例

let calendar;

$: {
  // Function to calculate the calendar which updates every change
  let calendarArr = [];
  const offset = new Date(
    selectedDate.getFullYear(),
    selectedDate.getMonth(),
    1
  ).getDay();
  //number of days in selected month
  const days =
    32 -
    new Date(selectedDate.getFullYear(), selectedDate.getMonth(), 32).getDate();
  //for each potential cell(empty cells + day cells)
  for (let d = 0; d < days + offset; d++) {
    //start new row if 0th, 7th, 14th etc day
    if (d % 7 == 0) calendarArr.push([]);
    //push cell into the row
    calendarArr[Math.trunc(d / 7)].push(
      d - offset < 0
        ? null
        : new Date(
            selectedDate.getFullYear(),
            selectedDate.getMonth(),
            d - offset + 1
          )
    );
  }
  console.log(calendarArr);
  calendar = calendarArr;
}

答案 1 :(得分:0)

您可以像这样立即调用它:

calendar = (() => { ... })()

但是更好的办法是给这个函数起一个名字,然后调用它:

function createCalendar() { ... }

calendar = createCalendar()