Array.fill() 方法用于将一个固定值填充到数组中的所有元素中。但它无法保留先前选择的月份日期,因为它只是简单地替换数组的所有元素。
如果你想要保留先前选择的月份日期,可以使用其他方法来实现。以下是一个示例代码,演示了如何保留先前选择的月份日期:
// 假设之前选择的月份日期存储在一个名为 selectedDates 的数组中
let selectedDates = [1, 5, 10, 15];
// 创建一个新的数组来保存填充后的结果
let filledDates = [];
// 假设你要填充的数组长度为 31 (即一个月的天数)
let arrayLength = 31;
// 使用 for 循环遍历数组长度
for (let i = 0; i < arrayLength; i++) {
// 如果当前索引 i 在 selectedDates 数组中存在,则将该值添加到 filledDates 数组中
if (selectedDates.includes(i+1)) {
filledDates.push(i+1);
} else {
filledDates.push(null); // 如果当前索引 i 不在 selectedDates 数组中,则填充为 null 或其他默认值
}
}
console.log(filledDates); // 输出结果: [1, null, null, null, 5, null, null, null, null, 10, null, null, null, 15, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null]
在上面的代码中,我们使用一个 for 循环遍历数组长度,然后判断当前索引是否在 selectedDates 数组中存在。如果存在,则将该值添加到 filledDates 数组中;如果不存在,则填充为 null 或其他默认值。
这样,我们就能够保留先前选择的月份日期,并且在填充数组时将其保留下来。