简体   繁体   English

从数组设置Google Spreadsheet单元格值,但所有值都相同

[英]Setting Google Spreadsheet cell values from array, but all values are the same

I am using Google Apps Script to try to get an array of dates and paste them into the cells on a Google Spreadsheet. 我正在使用Google Apps脚本尝试获取日期数组并将其粘贴到Google Spreadsheet的单元格中。

I am able to get the data into an array, and when I use the logger, I can see that the dates are incrementing, as is the array.length. 我能够将数据放入一个数组,当我使用记录器时,可以看到日期在增加,array.length也是如此。

When I use .setValues to paste the contents of the array into the spreadsheet, I get the same value in every cell. 当我使用.setValues将数组的内容粘贴到电子表格中时,我在每个单元格中都得到了相同的值。 (oldestDate in the code is just another date variable set earlier on. It is created using a new Date(date string) constructor, so is a valid date. (代码中的oldestDate只是之前设置的另一个date变量。它是使用new Date(date string)构造函数创建的,因此也是有效的日期。

  var today = new Date();
  var testDate = new Date(oldestDate);
  Logger.log(oldestDate);
  Logger.log(testDate);
  Logger.log("Loop Starts");
  var storage = [];
  var cols=0
  while (Date.parse(testDate) < Date.parse(today))
  {
    storage.push(testDate);
    Logger.log(testDate); //This is giving the same output as vvvvv
    Logger.log(storage[cols]); //This is giving the same output as ^^^^^
    Logger.log("Storage Length: "+storage.length); //This is incrementing
    testDate.setDate(testDate.getDate() +1);
    cols++;
  }

  var expensesDump = expenses.getSheetByName("Dump");
  expensesDump.getRange(1, 1, 1, cols).setValues([storage]); //This is populating every cell with "27/05/2013"

When you push an object (in this case, a date object) into an array, you are pushing a reference to that object: 当您将一个对象(在这种情况下,是一个日期对象)推入数组时,您正在推向对该对象的引用:

Do objects pushed into an array in javascript deep or shallow copy? 对象是否以javascript的深层或浅层副本推入数组?

The second answer in that link suggests that if a new object is assigned to the variable that is referenced by push(), then it is "disconnected" from previous invocations of push(). 该链接中的第二个答案表明,如果将新对象分配给push()引用的变量,则该对象将与先前push()的调用“断开连接”。 Therefore a solution might be (inside the while loop): 因此,一种解决方案可能是(在while循环内):

testDate = new Date(testDate);
testDate.setDate(testDate.getDate()+1);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM