在Svelte3和Javascript中,如何将复杂的计算数组返回给我的arrow函数?
自从Svelte v3发布以来,我一直在尝试将我的v2代码翻译成新版本。我已将计算部分转换为Javascript箭头函数。我想将函数返回的值设置为arrow函数所在的同一个变量。我还试着做:在Svelte3和Javascript中,如何将复杂的计算数组返回给我的arrow函数?,javascript,arrays,arrow-functions,svelte,Javascript,Arrays,Arrow Functions,Svelte,自从Svelte v3发布以来,我一直在尝试将我的v2代码翻译成新版本。我已将计算部分转换为Javascript箭头函数。我想将函数返回的值设置为arrow函数所在的同一个变量。我还试着做: calendar=()=>{…} 但在这种情况下,浏览器会解释箭头 函数作为默认方法 $:日历=>{ //函数用于计算每次更改都会更新的日历 设calendarArr=[]; 常量偏移量=新日期( selectedDate.getFullYear(), selectedDate.getMonth(), 1.
calendar=()=>{…}
但在这种情况下,浏览器会解释箭头
函数作为默认方法
$:日历=>{
//函数用于计算每次更改都会更新的日历
设calendarArr=[];
常量偏移量=新日期(
selectedDate.getFullYear(),
selectedDate.getMonth(),
1.
).getDay();
//所选月份的天数
常数天=
32 -
新日期(selectedDate.getFullYear(),selectedDate.getMonth(),32.getDate();
//对于每个潜在单元格(空单元格+日单元格)
对于(设d=0;d我想将其设置为日历值
};
您可以像这样立即调用它:
calendar = (() => { ... })()
但更好的做法是为该函数命名,然后调用它:
function createCalendar() { ... }
calendar = createCalendar()
反应语句($:
)不必是计算结果为单个值的表达式。您可以在reactive语句中计算calendarr
,然后将该值分配给组件中的另一个变量
示例
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;
}
let日历;
$: {
//函数用于计算每次更改都会更新的日历
设calendarArr=[];
常量偏移量=新日期(
selectedDate.getFullYear(),
selectedDate.getMonth(),
1.
).getDay();
//所选月份的天数
常数天=
32 -
新日期(selectedDate.getFullYear(),selectedDate.getMonth(),32.getDate();
//对于每个潜在单元格(空单元格+日单元格)
对于(设d=0;d
这一点非常正确。更进一步说,我们甚至不需要临时变量-您可以在顶部执行calendar=[]
而不是let calendarr=[]
,然后将对calendarr
的后续引用替换为calendar
。