按条件拼接元素后如何再次恢复全数组?

How to restore full array again after splice an element by condition?

提问人:Phil-Absynth 提问时间:11/1/2023 最后编辑:Phil-Absynth 更新时间:11/1/2023 访问量:33

问:

我有一个动态表,并希望每月的每一天都有一个随机数组元素。对于每天,我可能需要按条件删除数组元素,但我需要再次拥有原始数组,以便第二天进行检查和选择。

以下函数包括迭代和条件,但它会在触发后删除所有迭代的数组元素。

function generateRandomSchedule(month) {
    if(!month) {
        month = localStorage.getItem('currentDutyMonth');
    }
    const monthNumber = moment().month(month).format('M');
    const year = localStorage.getItem('currentYear');
    const daysInMonth = moment(`${year}-${monthNumber}`, 'YYYY-MM').daysInMonth();

    for(let i=1; i<daysInMonth+1; i++) {
        let date = `${moment(i, 'D').format('DD')}.${monthNumber}.`;
        const keys = Object.keys(localStorage).filter(key => key.includes(date) && !key.startsWith(month));
        keys.forEach((key) => {
            let keyValue = localStorage.getItem(key);
            if(key.includes('Urlaub') && dutyUserArray.includes(keyValue)) {
                let index = dutyUserArray.indexOf(keyValue);
                if(index > -1) {
                    dutyUserArray.splice(index, 1);
                }
            }
            if(key.includes('Spaet') && dutyUserArray.includes(keyValue)) {
                let index = dutyUserArray.indexOf(keyValue);
                if (index > -1) {
                    dutyUserArray.splice(index, 1);
                }
            }
        })

        let randomName = dutyUserArray[Math.floor(Math.random() * dutyUserArray.length)];
        let objectId = document.getElementById(`tdMa${date}`);
        objectId.value = randomName;

        localStorage.setItem(`${month}_tdMa${date}`, randomName);
    }
}

一旦选择了 a,我就会尝试撤消拼接,或者比保留原始阵列更好的解决方案。randomNamesplice()

javascript 数组 迭代 momentjs

评论

0赞 pilchard 11/1/2023
你可以简单地filter()数组吗?还是在你之前克隆它?有点不清楚你在做什么。forEach()
0赞 Phil-Absynth 11/2/2023
@pilchard感谢您的提醒。是的,在这种情况下,当然是更好的选择。不知道为什么我没有想到这一点。filter()

答: 暂无答案