Cell.getValue 没有正确比较值

Cell.getValue is not comparing values correctly

我是 google 应用程序脚本的新手,我 运行 遇到了问题。当我尝试将单元格值与两个整数进行比较时,它每次都有效。在我的电子表格中,只有少数几个值符合这些限制条件。这是我的代码:

  function CHECK_CORRELATION() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var sheet = ss.getActiveSheet();
    var rangeData = sheet.getDataRange();
    var lastColumn = rangeData.getLastColumn();
    var lastRow = rangeData.getNumRows();
    var counter = 0;
    var counter2 = 0;
    var values = rangeData.getValues()
    for (var j = 2; j <= lastRow; j++){
      var cell = sheet.getRange(j, 8)
      if (cell.isBlank()) {
        continue;
      } else {
        if (0.9<=cell.getValue()<=1.1){
          Logger.log(cell.getValue());
          counter++;
        }
        counter2++;
      }
    }
    Logger.log(counter)
    Logger.log(counter2)
    if (counter>(counter2/2)) {
      return "The idea that a student will have motivation and has a part time job co-occur"
    } else {
      return "The idea that a student will have motivation and has a part time job does not co-occur"
    }
  }

This is the logger

它表明 counter 是 62 并且 counter2 是 62,尽管它不应该是。

任何帮助将不胜感激!

你已经很棒了!我刚刚稍微清理了你的 for 循环。 我假设您的数据在第 8 列,对吗?

如果这解决了您的问题,请告诉我。

function CHECK_CORRELATION() 
{
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  var lc = sheet.getLastColumn();
  var lr = sheet.getLastRow();
  var rangeData = sheet.getRange(2, 1, lr -1, lc);
  var lastColumn = rangeData.getLastColumn();
  var lastRow = rangeData.getNumRows();
  var counter = 0;
  var counter2 = 0;
  var values = rangeData.getValues();
  
  for (var j = 0; j < values.length; j++)
  {
    var row = values[j];
    var dataToCheck = row[7];
    if ((dataToCheck != "" || dataToCheck != undefined) && dataToCheck >= 0.9 && dataToCheck <= 1.1)
    {
      counter++;
      }
      else
      {
        counter2++;
      }
      
    }
  
  Logger.log(counter)
  Logger.log(counter2)
  if (counter>(counter2/2)) 
  {
    return "The idea that a student will have motivation and has a part time job co-occur"
  } 
  else 
  {
    return "The idea that a student will have motivation and has a part time job does not co-occur"
  }
}

这个表达式并不像你想的那样有效:

0.9<=cell.getValue()<=1.1

以上是因为 <= 是一个需要两个操作数的 conditional operator,所以表达式将第一个比较的结果(真或假)与一个数字进行比较。

尝试将上面的表达式替换为

0.9 <= cell.getValue() && cell.getValue() <= 1.1

&&logical operator AND