简体   繁体   English

使用 Google Apps 脚本从数组中获取最后一个值

[英]Get last value from an array using Google Apps Script

I need to get last value from an array and I keep getting this error when I use slice我需要从数组中获取最后一个值,并且在使用 slice 时不断收到此错误

TypeError: Cannot find function slice in object Sun Jul 23 2017 00:00:00 GMT+0100 (BST).类型错误:在 object 中找不到 function 切片 2017 年 7 月 23 日星期日 00:00:00 GMT+0100 (BST)。 (line 15, file (第 15 行,文件

If I use length -1 I get NaN.如果我使用长度 -1,我会得到 NaN。

This is the code I am using it.这是我正在使用的代码。

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getSheetByName("Data");
  var range = sheet.getDataRange();
  var values = range.getValues();
  var today = new Date(Date.now());
   today.setHours(0,0,0,0);
    Logger.log(today);

var setTotal;
var getToday = values[4].map(Number).indexOf(+today);
Logger.log(getToday);
for (i = 0; i < values.length; i++) {
 var getTotal = values[i][getToday];
       Logger.log(getTotal.slice(-1)[0]); 
 }
}

... and this is the table ...这是桌子

full table满桌

So I need when it match the current day (today) to retrieve last value from that array (column) which is the Total for that day.所以我需要在它与当天(今天)匹配时从该数组(列)中检索最后一个值,这是当天的总计。

Thank you谢谢

Kind regards,亲切的问候,

getTotal is always already a singular value. getTotal始终已经是一个奇异值。
Also the way you find your column is brittle due to timezones because you normalize only one date. 同样,由于时区的原因,您找到列的方式也很脆弱,因为您只能对一个日期进行标准化。
If you do it with both dates (which needs to be handled safely unless you want to do index constraints) your column finding approach works. 如果同时使用两个日期(除非要进行索引约束,否则必须安全地进行处理),所以列查找方法有效。

function getTodaysTotal() {
  function toUtcMidnight(date) {
    try {return date.setHours(0,0,0,0);}
    catch(e) {return;}
  }

  var values = SpreadsheetApp
      .getActiveSpreadsheet()
      .getSheetByName("Data")
      .getDataRange()
      .getValues();

  var today = toUtcMidnight(new Date());
  var todaysColumn = values[4].map(toUtcMidnight).map(Number).indexOf(+today);
  var output = values[values.length - 1][todaysColumn];
  return values[values.length - 1][todaysColumn];
}

You can use the method .pop() that returns and removes the last element from an array.您可以使用.pop()方法返回并删除数组中的最后一个元素。

Make a copy of the original array first and use .pop() method and assign it to a new value.首先复制原始数组并使用.pop()方法并将其分配给新值。

var myArray = myArrayCopy
var lastArrayObject = myArrayCopy.pop()

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

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