在 Apps 脚本中将日期推送到数组时出错

Error while pushing Dates to Array in Apps Script

这就是函数(我觉得几个小时前我做了同样的事情,输出是我所期待的)

function errorFunction() {
  let master = []

  let a = [1,2] //a simple array to loop over

  a.forEach(function(b) {
    let theDate = Date.today() // 8th Sep 2021
    let i = 0
    while (i<2) {
      theDate = Date.parse(theDate).addDays(1)
      Logger.log(theDate) // dates are alternating between 9th and 10th september
      master.push([b,i,theDate])

      i = i+1
    }

  })
  
  Logger.log(master) // all dates are 10th september
}

代码将 9 月 9 日和 9 月 10 日推送到数组。但是数组的输出只有9月10日。

我的期望:

[
  [1.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
  [1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 0.0, Fri Sep 9 00:00:00 GMT+05:30 2021],
  [2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]

我得到的输出:

[
  [1.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [1.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 0.0, Fri Sep 10 00:00:00 GMT+05:30 2021],
  [2.0, 1.0, Fri Sep 10 00:00:00 GMT+05:30 2021]
]

我正在使用最新版本的 DateJs 库。

不确定你为什么需要那个库,这个片段可以完成工作:

const errorFunction = () => {
  const days = [1, 2];
  const i = [0, 1];
  const today = new Date();
  const addDays = (date, numDays = 1) =>
    new Date(new Date().setDate(date.getDate() + numDays));
  return days.reduce((acc, day) => {
    return [...acc, ...i.map(item => [day, item, addDays(today, day)])];
  }, []);
};

console.log(errorFunction());

让我知道这是否是您所期待的。

如果将 Date 对象传递给 DateJSparse() 方法,它将 return 对象(link), and the addDate() method also does not create a new object (link).因此,当您为每个 b 值创建一个新的 theDate 对象时,您在 while 循环中修改了 same 对象,并引用了它进入 master 数组。

解决方法是每次修改theDate时都创建一个新的Date对象。例如,更改此行:

theDate = Date.parse(theDate).addDays(1)

...为此:

theDate = new Date(theDate.valueOf()).addDays(1)

...或者这个(DateJS 定义了一个 clone() 方法):

theDate = theDate.clone().addDays(1)

这将在添加 1 天之前克隆 theDate 对象。

正如@kol 指出的那样,我将引用放入数组中。

所以我没有参考,而是这样做了:

function errorFunction() {
  let master = []

  let a = [1,2] //a simple array to loop over

  a.forEach(function(b) {
    let theDate = Date.today() // 8th Sep 2021
    let i = 0
    while (i<2) {
      theDate = Date.parse(theDate).addDays(1)
      Logger.log(theDate) // dates are alternating between 9th and 10th september
      master.push([b,i,new Date(theDate)])

      i = i+1
    }

  })
  
  Logger.log(master) // all dates are 10th september
}