gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 22:59:00 25 4
gpt4 key购买 nike

自 Svelte v3 的新版本发布以来,我正在尝试将我的 v2 代码转换为新版本。我已将计算部分翻译成 Javascript 箭头函数。我想将函数的返回值设置为箭头函数所在的同一变量。我也试过这样做:

日历 = () => {...}

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

$: 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
};

最佳答案

响应式语句 ($:) 不必是求值为单个值的表达式。您可以在响应语句中计算 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;
}

关于javascript - 在 Svelte3 和 Javascript 中,如何将复杂的计算数组返回给我的箭头函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56012073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com