【问题标题】:clear array while inside loop javascript在循环javascript中清除数组
【发布时间】:2021-12-17 01:35:24
【问题描述】:

我有这个循环:

for (let i = 0; i < rows.length; i++) {
            let sessionString = rows[i][weekday];
            //finalSessionString is the variable for splitting the string into 4 parts
            const finalSessionString = sessionString.split('|');
            //finalSessionString0 is the string that holds the value of (ex) 01 11 * * 1
            const finalSessionString0 = finalSessionString[0]
            //finalSessionStringPhoneNumber gets phone number from finalSessionString
            const finalSessionStringPhoneNumber = finalSessionString[1]
            //finalSessionStringName is getting the name of the person training
            const finalSessionStringName = finalSessionString[2]
            //finalSessionStringTrainerName is getting the name of the trainer
            const finalSessionStringTrainerName = finalSessionString[3]
            console.log("kk: " + finalSessionString[1])
            console.log(finalSessionString0)
            console.log(finalSessionStringPhoneNumber)
            console.log(finalSessionStringName)
            console.log(finalSessionStringTrainerName)
            var textJob = new cronJob( finalSessionString0, function(){
                client.messages.create( { to: finalSessionStringPhoneNumber, from:'12055578708', body:'hello ' + finalSessionStringName + ', Your training session just finished with ' +  finalSessionStringTrainerName}, function( err, data ) {
                    if (err) {
                        console.log("err: " + err)
                    } 
                    console.log(data)
                });
            },
            null, true)
            finalSessionString.length = 0
        }

finalSessionString 是一个数组,它会产生如下响应:

 [
  '05 10 * * 2',
  '1234567890',
  'Gianluca A',
  'gianluca@mmm.com'
]

所以在我将数组拆分为多个部分后,我希望它清除数组长度,因为我还在运行一个每 45 秒运行一次的 cronjob,所以每 45 秒它就会向数组中插入一个新值!因此,每次将新记录插入数组后,我都需要先清除它。这就是我在这里尝试做的事情

finalSessionString.length = 0

但它不起作用,因为在运行 5 轮 cronjob 后我收到了 5 条短信。那么我该如何解决呢?

【问题讨论】:

  • 将(只读)长度设置为零将不起作用。你只需要finalSessionString = [](另外,你为什么称数组为“finalSessionString”?)
  • 您需要重新考虑设计,您不应该为行中的每个项目添加一个 cronjob,而应该为行中的所有项目添加一个 cronjob
  • @ChrisG 谢谢。变量名现在只是暂时的,但我同意它们很糟糕,哈哈
  • @LawrenceCherone 老实说,我很难将我的想法围绕在我想要做的概念上,我知道 100% 这不是正确的方法。如果您愿意帮助我找到更好的解决方案,我们可以在其他地方聊天?
  • @LawrenceCherone stackoverflow.com/questions/69804783/… 这是我解释整个情况的另一个问题。也许你可以看看那个?

标签: javascript node.js arrays cron


【解决方案1】:

如果你只是想在 Cron 作业之前清除数组

finalSessionString = [ ];
finalSessionString.push(value);

【讨论】:

  • 我用了你说的。我很感激你的回答。我实际上认为这是另一个问题,我只是无法弄清楚。你能看到我的另一个问题吗?也许我做错了什么。 stackoverflow.com/questions/69804783/…
猜你喜欢
  • 2013-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-10-21
相关资源
最近更新 更多