【问题标题】:Function mutates an object argument after execution函数在执行后改变对象参数
【发布时间】:2019-08-28 14:31:02
【问题描述】:

我有一个函数,它接受一个对象参数并且应该从这个参数生成一个字符串值。我需要在另一个函数中使用这个参数,但是在执行第一个函数时,参数会改变。

这是接受对象参数的函数

export const  generateCron(cronRules: any): string {
   const cronKeys: Array<string> = ['minute', 'hour', 'day', 'month', 'year'];
   cronKeys.forEach(key => {
     if (!cronRules[key]) {
       cronRules[key] = '*';
     }
   });
   const { minute, hour, day, month, year } = cronRules;
   const cron: string = `${minute} ${hour} ${day} ${month} ${year}`;
   return cron;
 }

这是调用函数的方式

    const { cron } = data;
    console.log(cron)
    const cronRules: string = generateCron(cron);
    console.log(cron)

假设我将 cron 对象设为 { minute: 1, hour: 2 } 函数按预期返回1 2 * * *。但安慰 cron 对象(第二个控制台)对象已更改为 { minute: 1, hour: 2, day: '*', month: '*', year: '*' }

有人可以帮我了解发生了什么

【问题讨论】:

  • croncronRulesgenerateCron 函数中,你这样做 cronRules[key] = '*'

标签: javascript node.js typescript express


【解决方案1】:

对象在javascript中是通过引用传递的,所以当你调用时

cronRules[key] = '*';

您正在更改传递给函数的“cron”对象。

您可以将它用于整个函数,而不是弄乱 cron 对象:

const { minute, hour, day, month, year } = cronRules;
const cron: string = `${minute || '*'} ${hour || '*'} ${day || '*'} ${month || '*'} ${year || '*'}`;
return cron;

在不修改原始“cron”对象的情况下完成相同的任务。

【讨论】:

    【解决方案2】:

    仅仅因为您在循环中迭代cronRules,您需要引用cronRules 并对其进行更改。

    const ref = JSON.parse(JSON.stringify(cronRules));
    
       const cronKeys: Array<string> = ['minute', 'hour', 'day', 'month', 'year'];
       cronKeys.forEach(key => {
         if (!ref[key]) {
           ref[key] = '*';
         }
       });
    
    

    【讨论】:

      【解决方案3】:

       cronRules[key] = '*';
      

      您正在改变传递给函数的对象,因为 javascript 是对象的传递引用语言

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-05-11
        • 2016-12-27
        • 1970-01-01
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 2013-03-27
        相关资源
        最近更新 更多